list comprehension - Haskell Does Not Evaluate Lazily takeWhile -
isqrt :: integer -> integer isqrt = floor . sqrt . fromintegral primes :: [integer] primes = sieve [2..] sieve (p:ps) = p : sieve [x | x <- ps, x `mod` p > 0] primefactors :: integer -> [integer] primefactors n = takewhile (< n) [x | x <- primes, n `mod` x == 0]
here code. think guessed trying do: list of prime factors of given number using infinite list of prime numbers. code not evaluate lazily.
when use ghci
, :l mycode.hs
, enter primefactors 24
, result [2, 3
( , cursor flashing there) there isn't further prelude>
prompt. think there problem there. doing wrong?
thanks.
takewhile
never terminates composite arguments. if n
composite, has no prime factors >= n
, takewhile
sit there.
apply takewhile
primes list , filter result n mod
x, this:
primefactors n = [x | x <- takewhile (<= n) primes, n `mod` x == 0]
(<=
used instead of <
maximum correctness, prime factors of prime number consist of number).
Comments
Post a Comment