Вопрос

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))
Это было полезно?

Решение

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.

Другие советы

If we apply the anonymous function, we get (map list d1 (range)). range without arguments, creates a list from 2 to infinity. So we're calling map with list as the function argument and d1 and a sequence from 0 to infinity as the other arguments. What map does is: it applies the given function to elements from the given sequences until one of the sequences runs out of elements. So the elements we get are (list first-element-of-d1 first-element-of-range), (list second-element-of-d1 second-element-of-range) and so on until we've been over every element in d1.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top