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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With