Open main menu

Wikibooks β

Clojure Programming/Examples/API Examples/do Macros

< Clojure Programming‎ | Examples‎ | API Examples



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


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

hi mum hi dad hi sister (nil nil nil)


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.