Rayne
Rayne

Reputation: 32625

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?

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.

Upvotes: 3

Views: 363

Answers (3)

zcaudate
zcaudate

Reputation: 14258

This is more succint:

 (doall (map println [1 2 3] [3 2 1]))

Upvotes: 1

pmf
pmf

Reputation: 7749

(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.

Upvotes: 4

Jonas
Jonas

Reputation: 19642

You can simply do

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

Upvotes: 11

Related Questions