Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why filter on a lazy sequence doesn't work in clojure?

Tags:

clojure

I am hoping to generate all the multiples of two less than 10 using the following code

(filter #(< % 10) (iterate (partial + 2) 2))

Expected output:

(2 4 6 8)

However, for some reason repl just doesn't give any output?

But, the below code works just fine...

(filter #(< % 10) '(2 4 6 8 10 12 14 16))

I understand one is lazy sequence and one is a regular sequence. That's the reason. But how can I overcome this issue if I wish to filter all the number less than 10 from a lazy sequence...?

like image 540
celeritas Avatar asked Sep 24 '14 06:09

celeritas


1 Answers

(iterate (partial + 2) 2)

is an infinite sequence. filter has no way to know that the number of items for which the predicate is true is finite, so it will keep going forever when you're realizing the sequence (see Mark's answer).

What you want is:

(take-while #(< % 10) (iterate (partial + 2) 2))
like image 116
Diego Basch Avatar answered Sep 30 '22 18:09

Diego Basch