跳转到内容

Clojure 编程/示例/API 示例/do 宏

来自维基教科书,开放的书籍,开放的世界
(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}

注意:doto 在修改后返回对象,非常方便。在上面的例子中,不需要变量绑定来访问结果对象。

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

在这里你可以看到使用 doto 比使用 let 创建临时绑定更具可读性。

华夏公益教科书