Last modified on 15 June 2009, at 03:13

Clojure Programming/Examples/API Examples/do Macros

doseqEdit

(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)))

doallEdit

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

hi mum hi dad hi sister (nil nil nil)

dorunEdit

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

hi mum hi dad hi sister nil

dotoEdit

(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.