【发布时间】:2010-10-27 12:38:30
【问题描述】:
我写了一个函数来检查一个数是否是素数:
prime n = prime' n 2 (floor (sqrt n))
where prime' n c u | n `mod` c == 0 = False
| c > u = True
| otherwise = prime' n (c+1) u
我不知道这个函数的类型签名应该是什么。一开始我以为应该是这样的:
prime :: Integral a => a -> Bool
但是编译时出现错误,因为sqrt 需要Floating a,而floor 需要RealFrac a 而不是Integral a。当我删除类型签名时,它会编译,但函数不起作用:
*Euler> :t prime
prime :: (Integral a, RealFrac a, Floating a) => a -> Bool
*Euler> prime 5
<interactive>:1:0:
Ambiguous type variable `t' in the constraints:
`Floating t' arising from a use of `prime' at <interactive>:1:0-6
`RealFrac t' arising from a use of `prime' at <interactive>:1:0-6
`Integral t' arising from a use of `prime' at <interactive>:1:0-6
Probable fix: add a type signature that fixes these type variable(s)
我怎样才能使这个功能起作用?
【问题讨论】:
-
哈,总理',大声读出来。 ;-)
-
先把它读成撇号,然后我才意识到素数:)
标签: haskell types type-inference