``````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
``````

``````*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)
``````

4 个答案:

``````prime :: (Integral a) => a -> Bool
prime n = prime' n 2 (floor (sqrt (fromIntegral n)))
where prime' n c u | n `mod` c == 0 = False
| c > u = True
| otherwise = prime' n (c+1) u
``````

``````prime n = prime' n 2
where prime' n c | n `mod` c == 0 = False
| c * c > n = True
| otherwise = prime' n (c+1)
``````

``````*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)
``````

``````instance (Integral a, RealFrac b, Floating b) => Integral (Either a b) where ...
instance (Integral a, RealFrac b, Floating b) => RealFrac (Either a b) where ...
instance (Integral a, RealFrac b, Floating b) => Floating (Either a b) where ...
``````

（您还必须添加`Num``Ord``Real``Fractional`等实例），然后`prime 5`将是可以接受，因为存在满足类型条件的`5 :: Either Integer Float`

``````sqrt :: (Floating a) => a -> a
``````

``````sqrt (2 :: Int)
``````