1 Oct 2010 01:33
Any clean way to avoid explicit recursion when creating nested loops?
Nathan Sorenson <nds6 <at> sfu.ca>
2010-09-30 23:33:49 GMT
2010-09-30 23:33:49 GMT
I was discussing this on the clojure channel, and it seems as though
avoiding explicit recursion is the idiomatic thing to do. Is there a
better way to define a function that loops over an arbitrary number of
sequences in a nested fashion, similar to the 'for' macro, without
relying on recursion?
This is the current approach, using recursion:
(defn nested [& seqs]
"returns lazy 'for'-like nesting of a seq of seqs."
(letfn [(nestrec [prefix [list & deeper-lists]]
(if deeper-lists
(mapcat #(nestrec (conj prefix %) deeper-lists)
list)
(map #(conj prefix %) list)))]
(nestrec [] seqs)))
so (nested (range) [:a :b]) returns [[0 :a][0 :b] [1 :a] [1 :b]
[2 :a] ... ]
--
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure <at> googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+unsubscribe <at> googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
(Continue reading)
RSS Feed