Laziness does not work properly

(defn seq-trial [] (map #(do (println "hello " %) (inc %)) (range 10))) (take 3 (seq-trial)) 

The above code, when evaluated, produces the following:

(hi 0 hi 1 hi 2 hi 3 hi 4 hi 5 hi 6 hi 7 hi 8 hi 9 1 2 3)

Since the map returns a lazy sequence, I expected it to be printed only -

(hi 0 hi 1 hi 2 1 2 3)

Why is the whole list ranked here?

+6
source share
1 answer

This is because of a performance optimization called chunking. Essentially, a sequence is realized in groups of n elements called pieces. This means that you need to take care of any side effects in your mapping function. The end result is correct, you still get a sequence of the right length.

The default block size is 32, so if you increase your range to a value that exceeds this, you will realize that this is a bit better:

 user> (defn seq-trial [] (map #(do (println "hello " %) (inc %)) (range 100))) user> (take 3 (seq-trial)) hello 0 ; 32 item 'chunk' realized... hello 1 ... hello 30 hello 31 (1 2 3) ; the expected returned value 

If you need to avoid chunking, options are available.

+8
source

All Articles