Search code examples
clojure

Why is the reduce function producing a result in reverse order?


I am trying to implement a map function through the reduce function. I am following the sample code that Rich Hickey had written in the presentation he had given on transducers.

(defn mapr [f coll] (reduce (fn [xs x] (cons (f x) xs)) () coll))

(println (mapr inc '(1 2 3 4 5))) ; (6 5 4 3 2)

However I'm failing to understand why the list is getting mapped in reverse order ?


Solution

  • It is because cons puts the item to the front of a seq. See https://clojuredocs.org/clojure.core/cons:

    (cons x seq)
    

    Returns a new seq where x is the first element and seq is the rest.

    So in your case 1 will be incremented to 2, then put to the beginning of an empty list, giving '(2). The next value to be processed by the reducing function is 2. It will be incremented to 3 then placed at the beginning of '(2), giving '(3 2), and so on...

    Note that my language is a little loose: each time the reduce function is called a new seq is returned i.e. cons creates a new list each time it is called.