Search code examples
clojureanonymous-functionseq

How does range work in this example?


Why is (range) in the following example able to reproduce index values? I would like to write a defn-defined function, but cannot see how this example works to reproduce what it does. I understand that # is creating an anonymous function.

So, assuming (def d1 [:a :b :c]) how is range generating indexes in the following?

(#(map list % (range)) d1)
((:a 0) (:b 1) (:c 2))

Solution

  • range returns an infinite sequence of integers, starting from zero. When map is passed two collection arguments, it calls f with two arguments, taking them pairwise from the collections. Thus, your f will be called once for each element x in d1, with two arguments: x, and its index in d1.

    As an aside, please paste code that works, or at least makes sense. The # is in a nonsense place, and the parens don't balance.