So I have devised the following function for seeing if a given number is a prime in Haskell (it assumes the first prime is 2):
isPrime k = length [ x | x <- [2..k], k `mod` x == 0] == 1
it has the obvious pitfall of continuing the evaluation even if it is divisible by several numbers :(. Is there any sane way of "cutting" the evaluation when it finds more than one solution, using list comprehensions?
Also, which other implementations would you you try on? I'm not looking for performance here, I'm just trying to see if there are other more "haskellish" ways of doing the same thing.
A quick change to your code that will 'short circuit' the evaluation, and relies on the laziness of Haskell Lists, is:
isPrime k = if k > 1 then null [ x | x <- [2..k - 1], k `mod` x == 0] else False
The very first divisor of k
will cause the list to be non-empty, and the Haskell implementation of null
will only look at the first element of the list.
You should only need to check up to sqrt(k)
however:
isPrime k = if k > 1 then null [ x | x <- [2..isqrt k], k `mod` x == 0] else False
Of course, if you are looking to do high-performance primality testing, a library is preferred.