Haskell 歧义类型
findMult lst n = [x | x <- lst, x `mod` n == 0]
primes num =
let n = [2..num]
x = ceiling (sqrt num)
nsqrt = [2..x]
not_prime = map (findMult n) nsqrt
in diff2 n (concat not_prime)
当我尝试运行它时出现以下问题
<interactive>:1:0:
Ambiguous type variable `t' in the constraints:
`RealFrac t' arising from a use of `primes' at <interactive>:1:0-8
`Floating t' arising from a use of `primes' at <interactive>:1:0-8
`Integral t' arising from a use of `primes' at <interactive>:1:0-8
Probable fix: add a type signature that fixes these type variable(s)
我尝试使用 fromIntegral 但我认为我使用不正确,因为这给了我编译错误。请帮忙。
这样做的目的是找到 num 之前的所有素数。
findMult lst n = [x | x <- lst, x `mod` n == 0]
primes num =
let n = [2..num]
x = ceiling (sqrt num)
nsqrt = [2..x]
not_prime = map (findMult n) nsqrt
in diff2 n (concat not_prime)
has the following problem when i try to run it
<interactive>:1:0:
Ambiguous type variable `t' in the constraints:
`RealFrac t' arising from a use of `primes' at <interactive>:1:0-8
`Floating t' arising from a use of `primes' at <interactive>:1:0-8
`Integral t' arising from a use of `primes' at <interactive>:1:0-8
Probable fix: add a type signature that fixes these type variable(s)
I tried using fromIntegral but i don't think i used correctly as that gives me compilation error. Please help.
The purpose of this is to find all the prime numbers up until num.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在需要浮点值的地方使用整数值时,您会收到类似这样的错误消息(反之亦然)。
在这种情况下,问题在于您在
num
上调用sqrt
(它采用浮点值作为参数),使编译器认为num
> 是浮点值。但也可以使用num
作为n
的上限,它是一个整数值列表(因为它用作findMult
的参数,需要整数值列表)。因此,在对
num
调用sqrt
之前,先调用fromIntegral
,如下所示:You get error messages like this when you use an integral value where a floating value was expected (or vice versa).
In this case the problem is that you're calling
sqrt
, which takes a floating point value as an argument, onnum
making the compiler thinknum
is a floating point value. But also usenum
as an upper limit forn
, which is a list of integral values (because it's used as an argument tofindMult
which needs a list of integral values).So before calling
sqrt
onnum
callfromIntegral
on it, like this:您可以不求平方根,而是求所有平方直到极限。
Instead of taking the square root, you can take all squares up to the limit.