I wrote the following function to decide if a number is prime or not.
isPrime :: Int -> Bool
isPrime n = and (map (\x -> (n `mod` x > 0))[2..(intSquareRoot n)])
intSquareRoot :: Int -> Int
intSquareRoot n = intSq n
where
intSq x
| x*x > n = intSq (x - 1)
| otherwise = x
I just got started with using Haskell so this piece of code may be hideous to anyone who is trained in using it. However, I am curious if this piece of code makes use of Haskell's lazy evaluation. this part
(map (\x -> (n `mod` x > 0))[2..(intSquareRoot n)])
will create a list of booleans, if just one of these is False (so if a number between 2 and the sqrt of n divides n) then the whole thing is False using the 'and' function. But I think the whole list will be created first and then the 'and' function will be used. Is this true? If so, how can I make this faster by using lazy evaluation, so that the function stops and returns false once it finds the first divisor of n. Thanks in advance for any help!
$instead of parens beforemap; it's really a nice tool :) - Bartek Banachewiczandyou can useany:any (\x -> nmod` x > 0) [2..intSquareRoot n].any` is equivalent to:any f = and . map f. - Bakuriuany f = or . map f. You were thinking aboutall f = and . map finstead. - chiintSquareRootis going to be incredibly slow for any sort of large input. You might want to consider a loop based on the old divide-and-average trick, instead. - Carl