Jump to content

Clojure Programming/Examples/API Examples/do Macros

From Wikibooks, open books for an open world

doseq

[edit | edit source]
(doseq [i [1 2 3 4]] (print i))

; This is an example of using destructuring to pair an index with each element of a seq.
(doseq [[index word] (map vector 
                          (iterate inc 0) 
                          ["one" "two" "three"])]
  (prn (str index " " word)))

doall

[edit | edit source]
user=> (doall (map #(println "hi" %) ["mum" "dad" "sister"]))

hi mum hi dad hi sister (nil nil nil)

dorun

[edit | edit source]
user=> (dorun (map #(println "hi" %) ["mum" "dad" "sister"]))

hi mum hi dad hi sister nil

(doto (new java.util.HashMap) (.put "a" 1) (.put "b" 2))
-> {a=1, b=2}

NB: doto returns the object after modification, which is very convenient. Consider in the above example no variable binding is required to access the resultant object.

(.addChild *scene-graph*
  (doto (KeyNavigatorBehavior.
         (-> *universe* .getViewingPlatform .getViewPlatformTransform))
    (setSchedulingBounds (BoundingSphere. (Point3d.) 10000.0))))

Here you can see it is much more readable using doto than the alternative which would be to create a temporary binding with let.