I’m trying to define an is_prime function in Haskell. Can anyone point out the issue with the use of the any function?
In addition, I know that the below code is naïve, but I am learning the language so starting with babysteps.
is_prime 0 = False
is_prime 1 = False
is_prime 2 = True
is_prime n = any [n `mod` k == 0 | k <- [2.. sqrt n]]
Type of
anyis(a -> Bool) -> [a] -> Bool, so it accepts a predicate and a collection. So you should rewrite your last case as for instancefromIntegralis necessary becausesqrt‘s type isFloating a => a -> awhile yournis an integer. Subsequently, withoutceilingthe second argument ofanywould beFloating t => [t]. This would break, as callingmod, whose type isIntegral a => a -> a -> a, on non-integral types is illegal.If you’d like to look for some other implementations, I can recommend for example this discussion.