Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two nested for of for and map?

When I need to generate a sequence which needs "two loops", is it better to do something like this:

(for [x (range 1 4)] (map #(* x %) (range 6 9)))

or something like this:

(for [x (range 1 4)] (for [y (range 6 9)] (* x y)))

Both give the same result:

((6 7 8) (12 14 16) (18 21 24))

Is one more idiomatic than the other and what are the differences between these two?

Also, is it possible to get the same result by nesting two map?

like image 457
Cedric Martin Avatar asked Dec 28 '22 01:12

Cedric Martin


1 Answers

Either is fine, but the second version scales better to arbitrary nesting levels.

Nesting map calls works, too:

user=> (map (fn [x] (map (fn [y] (* x y)) (range 6 9))) (range 1 4))
((6 7 8) (12 14 16) (18 21 24))

You cannot nest the shortcut function syntax, though.

By the way, just in case you actually need more set-comprehension-like semantics, for also has nesting built-in. The result is somewhat different:

user=> (for [x (range 1 4), y (range 6 9)] (* x y))
(6 7 8 12 14 16 18 21 24)
like image 100
Matthias Benkard Avatar answered Jan 12 '23 12:01

Matthias Benkard