0
votes

Well I'm new in clojure and I was reviewing the literature of the function mapcat in (http://clojuredocs.org/clojure.core/mapcat) and I found the following sample:

(mapcat (fn [[k v]] 
                 (for [[k2 v2] v] 
                   (concat [k k2] v2)))
         '{:a {:x (1 2) :y (3 4)}
           :b {:x (1 2) :z (5 6)}})

((:a :x 1 2) (:a :y 3 4) (:b :x 1 2) (:b :z 5 6))

I tried to understand but I got confused how does the key and values work, I'm not sure what is the exactly value of k, k2, v and v2 when the functions for and concat use them.

Thanks for your help.

2

2 Answers

1
votes

Perhaps this example will help you understand what mapcat does, but it's not a great example of well-written code: it is a rather confusing way to write the much-simpler

(for [[k v] '{:a {:x (1 2) :y (3 4)}
              :b {:x (1 2) :z (5 6)}}
      [k2 v2] v]
  (list* k k2 v2))

Mixing the mapcat and the for together in the same place makes it harder to see that all that's happening is a nested sequence comprehension.

0
votes

The function is applied to each key-value tuple of the incoming map. The [[k v]] destructures the tuple, so that in the first case, k will have the value :a, and v the value {:x (1 2) :y (3 4)}.

The for loop the iterates through tuples in v, destructuring again, so that in the first case, k2 will be :x and v2 will be (1 2).

This is passed to concat, so that our first entry will be (:a :x 1 2)