Posted By

narkisr on 04/03/09


Tagged

reduce clojure doseq


Versions (?)

Clojure alternative doseq implementation (using reduce).


 / Published in: Lisp
 

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

  1. (defn permutations
  2. "creates a sequence of all permutations of multiple sequences"
  3. [curr-seq & rest-seqs]
  4. (if (nil? rest-seqs)
  5. (map #(cons % '()) curr-seq)
  6. (reduce concat (map (fn [curr-seq-val] (map #(cons curr-seq-val %)
  7. (apply permutations rest-seqs))) curr-seq))))
  8.  
  9. (defmacro mydoseq
  10. "Uses reduce to implement doseq"
  11. [forms & body]
  12. (let [form-pairings (partition 2 forms)
  13. vars (vec (map #(first %) form-pairings))
  14. assignments (map #(second %) form-pairings)]
  15. `(reduce (fn ~'[nothing args] (apply (fn ~vars ~@body) ~'args))
  16. nil
  17. (permutations ~@assignments))))
  18.  
  19. user=> (doseq [a '(3 4 5 6)] (println (+ a 2)))
  20. 5
  21. 6
  22. 7
  23. 8
  24. nil
  25. user=> (mydoseq [a '(3 4 5 6)] (println (+ a 2)))
  26. 5
  27. 6
  28. 7
  29. 8
  30. nil

Report this snippet  

You need to login to post a comment.