如何在ClojureScript中使用命名参数?

Zub*_*air 5 clojure clojurescript

在clojure中,我可以使用defnk来获取命名参数.如何在ClojureScript中实现相同的功能?

fog*_*gus 11

ClojureScript中命名的args功能与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
Run Code Online (Sandbox Code Playgroud)

如果您需要默认值,请将原始内容更改为:

(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
Run Code Online (Sandbox Code Playgroud)

这与Clojure的好答案有关- 命名参数

  • `defnk`在clojure.contrib中定义.它是在Clojure 1.2添加完整的地图解构绑定之前创建的.`defnk`现在应该被认为是过时的(事实上整体的clojure.contrib与Clojure 1.3不兼容.) (3认同)