Doseq evaluates 1 x for every y. Is there any way to make it evaluate 1 x for 1 y and so on in Clojure?

StackOverflow https://stackoverflow.com/questions/1216668

  •  06-07-2019
  •  | 
  •  

Question

I wasn't really sure how to phrase the name of this thread, so if you can clarify it any, please do so.

My example code is this:

(doseq [x [1 2 3] y [3 2 1]] (println (str x y)))

The output of that code is:


13
12
11
23
22
21
33
32
31
nil

I understand that list comprehensions, and doseq both evaluate like this. Is there another way to do this, so that instead of 1 element of x being used for every element of y, and so on, 1 element of x is used with 1 element of y and so on, so that the output would instead be:


13
22
31

Sorry if I'm not phrasing this right, I just can't seem to put it in words right.

EDIT: I think you can do this in Haskell with list comprehensions and a language extension. ParallelListComps or something.

Was it helpful?

Solution

You can simply do

(doseq [[x y] (map vector [1 2 3] [3 2 1])] 
  (println (str x y)))

OTHER TIPS

(partition 2
  (interleave [1 2 3] [3 2 1]))

interleave yields a sequence of alternating elements from the given sequences and partition groups this sequence into sequences of n elements.

This is more succint:

 (doall (map println [1 2 3] [3 2 1]))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top