J. Kim
J. Kim

Reputation: 105

Why this code return empty list or fail? Haskell

primes :: [Int]
primes = sieve [2..]

sieve :: [Int] -> [Int]
sieve (p:xs)= p:sieve[x|x<-xs,x `mod` p /= 0]

f :: Int->Int
f n = head [x|x<-[0,(product (filter (<n) primes))..],x/=0,sum (map (x `mod`) [1..n]) == 0]

load into GHCi and type "f 20" fail...... plz help me

Upvotes: 1

Views: 164

Answers (1)

hammar
hammar

Reputation: 139930

The problem is with filter (< n) primes. Since primes is an infinite very long1 list, this takes a long time to terminate since it doesn't know that (< n) will eventually return False for all primes past a certain point in the list, so it has to keep checking the entire list.

> filter (< 20) primes
[2,3,5,7,11,13,17,19^CInterrupted.

Use takeWhile (< n) primes instead.

> takeWhile (< 20) primes
[2,3,5,7,11,13,17,19]

1 It's finite because of the type [Int]. If it was [Integer], it would be infinite.

Upvotes: 10

Related Questions