Return to Snippet

Revision: 12995
at April 3, 2009 12:13 by narkisr


Initial Code
(defn permutations
  "creates a sequence of all permutations of multiple sequences"
  [curr-seq & rest-seqs]
  (if (nil? rest-seqs)
    (map #(cons % '()) curr-seq)
    (reduce concat (map (fn [curr-seq-val] (map #(cons curr-seq-val %)
(apply permutations rest-seqs))) curr-seq)))) 

(defmacro mydoseq
  "Uses reduce to implement doseq"
  [forms & body]
  (let [form-pairings (partition 2 forms)
        vars (vec (map #(first %) form-pairings))
        assignments (map #(second %) form-pairings)]
    `(reduce (fn ~'[nothing args] (apply (fn ~vars ~@body) ~'args))
             nil
             (permutations ~@assignments)))) 

user=> (doseq [a '(3 4 5 6)] (println (+ a 2)))
5
6
7
8
nil
user=> (mydoseq [a '(3 4 5 6)] (println (+ a 2)))
5
6
7
8
nil

Initial URL


Initial Description
Two alternative implementations of Clojure doseq utilising map & reduce functions (http://groups.google.com/group/clojure/browse_thread/thread/d6eb04c87bdd000f?hl=en).

Initial Title
Clojure alternative doseq implementation (using reduce).

Initial Tags


Initial Language
Lisp