【发布时间】:2010-12-11 05:04:19
【问题描述】:
所以,我正在学习 Haskell,并且经常陷入与类型/类型类相关的错误。一些非常明显的愚蠢错误,还有一些让我觉得 haskell 不适合我。反正我有这段代码……
pfactors' ps n
| p > (sqrt n) = []
| m == 0 = p : (pfactors' ps q)
| otherwise = pfactors' (tail ps) n where
p = head ps
(q, m) = divMod n p
pfactors = pfactors' primes
main = print $ pfactors 14
(一些背景知识:pfactors 函数应该接受一个数字并返回一个素数列表,这些素数是给定数字的素数。primes 是一个无限的素数列表)
这给了我这个错误:
p47.hs:10:11:
Ambiguous type variable `a' in the constraints:
`Floating a' arising from a use of `pfactors'' at p47.hs:10:11-26
`Integral a' arising from a use of `primes' at p47.hs:10:21-26
Possible cause: the monomorphism restriction applied to the following:
pfactors :: a -> [a] (bound at p47.hs:10:0)
Probable fix: give these definition(s) an explicit type signature
or use -XNoMonomorphismRestriction
现在我明白这是p < (sqrt n) 部分的问题,因为它是唯一与Floating 有关的部分。如果我将其更改为 p < n 一切正常,我会得到正确的答案。但是我真的很想检查平方根,那我该怎么做呢?
顺便说一句,这不是作业,如果感觉像,这是我在 projecteuler.net 上解决第 47 个问题的尝试
感谢您的帮助。
而且,请不要给我所说的项目欧拉问题的解决方案,我想尽可能自己做:)。谢谢。
【问题讨论】: