The condition x `mod` y == 0 for y in [2, 3 .. floor x^0.5]
is not syntactically valid in Haskell. Haskell for example has no for
keyword. Furthermore even in Python the above would not work, since then you are constructing a generator.
You can make use of all :: Foldable f => (a -> Bool) -> f a -> Bool
to check if x
is not dividable by all values in a list. That list is then a list [ 2 .. √x ]
.
Working with (^) :: (Num a, Integral b) => a -> b -> a
will not work, since the exponent should be of a type that is a member of the Integral
typeclass. If we make use of (**) :: Floating a => a -> a -> a
the first operand should be of a type that is a member of the Floating
typeclass. We can convert Int
s to a Float
, but that is usually not very safe, since there can be rounding errors.
It therefore might be better to make use of takeWhile :: (a -> Bool) -> [a] -> [a]
to take elements, as long as a certain condition holds. So we can here check with:
Prelude> takeWhile (\y -> y*y <= 20) [2 ..]
[2,3,4]
So we can implement the prime checker as:
isPrime :: Int -> Bool
isPrime x
| x <= 1 = False
| otherwise = all ((/=) 0 . mod x) (takeWhile (\y -> y*y <= x) [2 .. ])