A few lazy sequences per card

Given the keys

:id :tag :name 

and three lazy sequences producing output in the form

 (id1 id2 id3 ...) (name1 name2 name3 ...) (type1 type2 type3 ...) 

what I need to do is get a sequence of cards in the form

 ({id: id1 :name name1 :type type1} {id: id2 :name name2 :type type2} {id: id3 :name name3 :type type3} ...) 

I tried various combinations of apply, map, assoc, etc., but did not get it.

+4
source share
3 answers

You only need map :

 (map (fn [id name type] {:id id :name name :type type}) (id1 id2 id3 ...) (name1 name2 name3 ...) (type1 type2 type3 ...)) 
+11
source

My answer is very similar to mtyaka's answer, but it is still a little shorter and more modular in my opinion.

 (map (fn [& vs] (zipmap [:id :name :type] vs)) (id1 id2 id3 ...) (name1 name2 name3 ...) (type1 type2 type3 ...)) 

Here, zipmap creates maps using a fixed sequence of keys and a sequence of variable values, which will be (id1 name1 type1) during the "first step", (id2 name2 type2) during the "second step, etc.

This will only work if your three lazy sequences are isolated from each other. If you have a sequence of lazy sequences, i.e. ((id1 id2 ...) (name1 name2 ...) (type1 type2 ...)) , then you will need to apply above in this seq, for example:

 (apply map (fn [& vs] (zipmap [:id :name :type] vs)) ((id1 id2 id3 ...) (name1 name2 name3 ...) (type1 type2 type3 ..))) 

Here apply simply adds the code map (fn [& vs] (zipmap [:id :name :type] vs)) at the front of the lazy sequence sequence, and this becomes an expression that needs to be evaluated. In other words, this leads to the same expression as the first block of code.

+6
source

I would go with:

 (map hash-map (repeat :id) seq1 (repeat :name) seq2 (repeat :type) seq3) 

Assuming seq1, seq2 and seq3 are your lazy sequences containing values โ€‹โ€‹for subsequent keys.

+1
source

All Articles