【发布时间】:2012-01-03 10:43:03
【问题描述】:
在 clojure 中,我可以使用 defnk 来获取命名参数。如何在 ClojureScript 中实现相同的功能?
【问题讨论】:
标签: clojure clojurescript
在 clojure 中,我可以使用 defnk 来获取命名参数。如何在 ClojureScript 中实现相同的功能?
【问题讨论】:
标签: clojure clojurescript
ClojureScript 中的命名参数功能与 Clojure 中的相同:
(defn f [x & {:keys [a b]}]
(println (str "a is " a " and b is " b)))
(f 1)
; a is and b is
(f 1 :a 42)
; a is 42 and b is
(f 1 :a 42 :b 108)
; a is 42 and b is 108
如果你想要默认值,那么把原来的改成:
(defn f [x & {:keys [a b] :or {a 999 b 9}}]
(println (str "a is " a " and b is " b)))
(f 1)
; a is 999 and b is 9
这与Clojure - named arguments的好答案有关
【讨论】:
defnk 在 clojure.contrib 中定义。它是在 Clojure 1.2 添加完整地图解构绑定之前创建的。 defnk 现在应该被认为是过时的(事实上,整体的 clojure.contrib 与未来的 Clojure 1.3 不兼容。)