Skip to content

Instantly share code, notes, and snippets.

@kgbu
Created October 4, 2010 07:00
Show Gist options
  • Select an option

  • Save kgbu/609331 to your computer and use it in GitHub Desktop.

Select an option

Save kgbu/609331 to your computer and use it in GitHub Desktop.
ghci> e: test.hs
is_prime :: (Integral a, RealFrac a, Floating a) => a -> Bool
is_prime x | x < 3 = True
| otherwise = not (any (mod0_p x) (candidates x))
mod0_p :: (Integral a) => a -> a -> Bool
mod0_p x y = (mod x y ) == 0
candidates :: (Integral t, Floating a, RealFrac a) => a -> [t]
candidates x = [y| y <- [2 .. (floor (sqrt x))]]
:load test.hs
Main> is_prime 6
interactive>:1:0:
Ambiguous type variable `t' in the constraints:
`Floating t'
arising from a use of `is_prime' at <interactive>:1:0-9
`Integral t'
arising from a use of `is_prime' at <interactive>:1:0-9
`RealFrac t'
arising from a use of `is_prime' at <interactive>:1:0-9
Probable fix: add a type signature that fixes these type variable(s)
@kgbu

kgbu commented Oct 4, 2010

Copy link
Copy Markdown
Author

なんでなのかしら。
intの世界から少しはみ出すとえらい目に会うな。

@kgbu

kgbu commented Oct 4, 2010

Copy link
Copy Markdown
Author

単純にfromIntegralという関数を使って型変換するしかないみたい。

is_prime :: (Integral a) => a -> Bool
is_prime x | x < 3 = True
| otherwise = not (any (mod0_p x) (candidates x))

mod0_p :: (Integral a) => a -> a -> Bool
mod0_p x y = (mod x y ) == 0

candidates :: (Integral t, Integral a) => a -> [t]
candidates x = [y| y <- [2 .. (floor (sqrt (fromIntegral x)))]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment