【发布时间】:2023-03-31 19:08:01
【问题描述】:
最终编辑:
我的最终功能是:
isPrime n = n > 1 && n < 4
|| n `mod` 2 /= 0
&& n `mod` 3 /= 0
&& length [x | x <- [5, 11..round (sqrt (fromIntegral n))], n `mod` x == 0 || n `mod` (x + 2) == 0] == 0
问题是我试图将n 视为sqrt n 中的Floating 和n mod x 中的Integral。所以我不得不做fromIntegral n 强制 n 被视为Integral 而不是Floating。
另外我只是搞砸了我的一些代码。
所以我有两个功能:
primes = filterPrime [2..]
where filterPrime (p:xs) = p : filterPrime [x | x <- xs, x `mod` p /= 0]
以上直接来自 haskell.org,例如 take 5 primes 的结果为 [2,3,5,7,11]
我的函数isPrime如下:
isPrime n = isPrime n = n > 1 && n < 4
|| (n `mod` 2 == 0 || n `mod` 3 == 0)
&& length [x | x <- [5, 11..round (n ** 0.5)], n `mod` x == 0 || n `mod` (x + 2) == 0] == 0
但是,当我打电话给isPrime 时,我得到了错误:
EulerMath.hs:6:33: error:
* No instance for (RealFrac Int) arising from a use of `round'
* In the expression: round (n ** 0.5)
In the expression: [5, 11 .. round (n ** 0.5)]
In a stmt of a list comprehension: x <- [5, 11 .. round (n ** 0.5)]
|
6 | && length [x | x <- [5, 11..round (n ** 0.5)], n `mod` x == 0 || n `mod` (x + 2) == 0] == 0
| ^^^^^^^^^^^^^^^^
EulerMath.hs:6:40: error:
* No instance for (Floating Int) arising from a use of `**'
* In the first argument of `round', namely `(n ** 0.5)'
In the expression: round (n ** 0.5)
In the expression: [5, 11 .. round (n ** 0.5)]
|
6 | && length [x | x <- [5, 11..round (n ** 0.5)], n `mod` x == 0 || n `mod` (x + 2) == 0] == 0
| ^^^^^^^^
EulerMath.hs:6:45: error:
* No instance for (Fractional Int) arising from the literal `0.5'
* In the second argument of `(**)', namely `0.5'
In the first argument of `round', namely `(n ** 0.5)'
In the expression: round (n ** 0.5)
|
6 | && length [x | x <- [5, 11..round (n ** 0.5)], n `mod` x == 0 || n `mod` (x + 2) == 0] == 0
| ^^^
我不知道如何正确注释isPrime 函数(阅读:我根本不知道如何正确注释)所以我没有收到此错误
【问题讨论】:
-
要注释你添加一行:
isPrime :: Int -> Bool. -
有纯粹的整数算法来求整数平方根的底。例如,请参阅here。所以你可以完全避免处理浮点数。
标签: haskell