Search code examples
clojuretransducer

Transduce: Why this transduce doesn't print anything


I have the following code, and I have expected it to print 1,2,3,4 on console, and return [true,true,true,true]. But it just return empty and doesn't print anything on console.

The logic is: it loop for (0..3), inc every element by 1, so I got (1..4), then run (map (fn[x] (println x) true)) it takes 1 from the lazy sequence, print 1, and return true, and take-while will output the result to [true], then take the next element of 2, print 2, return [true,true], etc. so the result should print 1,2,3,4 to console, and return [true,true,true,true]. But actually, it prints nothing and return []. How to understand this?

(transduce (comp (take-while true?)
                 (map (fn[x] (println x) true))
           conj
           []
           (map inc (range 4)))

Solution

  • Thats because

    Composition of the transformer runs right-to-left but builds a transformation stack that is applied left-to-right (filtering happens before mapping in this example).

    Look here for more :http://clojure.org/transducers