Find the sum of all the primes below two million.
Prelude Data.Numbers.Primes> sum $ takeWhile (<= 2000000) primes
142913828922
cf) from StackOverflow. Thank you to bennofs & Zeta
my first code is: sum $ [x | x <- primes, x < 2000000] but this is not work.
Zeta and bennofs told me my code is same to filter (<= 2000000) primes.
They (esp. bennofs) told me that "The problem is that GHCi can't know that your list of
primes is ordered"> takeWhile (<= 10) primesThank you so much to Zeta and bennofs.
[2,3,5,7] -- takeWhile stops after it encounters 7,
because the predicate becomes false
> filter (<= 10) primes
[2,3,5,7 -- filter cannot stop,
because there might still be a number later in the list that satisfies the predicate.
This is what the list comprehension does.
댓글 없음:
댓글 쓰기