以下内容返回True(因为2147483647是素数)。为什么Haskell在扩展时抱怨ambigous类型?
length [f | f <- [2..(floor(sqrt 2147483647))], 2147483647 `mod` f == 0 ] == 0
为什么它不起作用,当我试图扩展它如下?
Prelude> [n | n <- [2..], length [f | f <- [2..(floor(sqrt n))], n `mod` f == 0 ] == 0 ]
<interactive>:1:39:
Ambiguous type variable `t' in the constraints:
`RealFrac t' arising from a use of `floor' at <interactive>:1:39-51
`Integral t' arising from a use of `mod' at <interactive>:1:56-64
`Floating t' arising from a use of `sqrt' at <interactive>:1:45-50
Probable fix: add a type signature that fixes these type variable(s)
虽然我不明白,为什么RealFrac会因使用floor而产生?我认为地板采用了RealFracs并制作了Integrals?再加上它没有抱怨上面的例子,我只输入更多的整数,就像我那样。
Prelude> :t floor
floor :: (RealFrac a, Integral b) => a -> b
Haskell的类型默认机制通常会处理这种歧义 - 例如,“Floating”的任何实例通常默认为“Double”。问题中的错误是由于排除默认类型的所有可能选项的约束。 –