【发布时间】:2026-01-22 16:25:02
【问题描述】:
我试过了:
composites=[c|c<-[4..], any (\p->(c`mod`p == 0)) (takeWhile (< (sqrt c)) primes)]
primes=2:[p|p<-[3..], not p `elem` (takeWhile (<p) composites)]
得到:
pad.hs:1:19:
No instance for (Num Bool) arising from the literal `4'
Possible fix: add an instance declaration for (Num Bool)
In the expression: 4
In the expression: [4 .. ]
In a stmt of a list comprehension: c <- [4 .. ]
pad.hs:1:30:
No instance for (Integral Bool) arising from a use of `divisible'
Possible fix: add an instance declaration for (Integral Bool)
In the first argument of `any', namely `(divisible c)'
In the expression: any (divisible c) (factors c)
In a stmt of a list comprehension: any (divisible c) (factors c)
pad.hs:3:43:
No instance for (Floating Bool) arising from a use of `sqrt'
Possible fix: add an instance declaration for (Floating Bool)
In the second argument of `(<)', namely `sqrt c'
In the first argument of `takeWhile', namely `(< sqrt c)'
In the expression: takeWhile (< sqrt c) primes
Failed, modules loaded: none.
我认为它正在处理什么类型的数字感到困惑,但我不确定。有什么建议吗?
【问题讨论】:
-
即使有来自
leftaroundabouts 答案的修复,您仍然无法获得您希望的结果。要了解原因,请考虑您的primes不可能只是未经过滤的[3..]列表。您在生成composites时也会犯该错误 -
在两个
takeWhile调用中应该是<=,而不是<。
标签: haskell compiler-errors primes