【问题标题】:How can I use named parameters in ClojureScript?如何在 ClojureScript 中使用命名参数?
【发布时间】:2012-01-03 10:43:03
【问题描述】:

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

【问题讨论】:

标签: clojure clojurescript


【解决方案1】:

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 中呢?
  • clojure 中默认没有这样的东西。它可能包含在 clojure.contrib 中(不知道是否包含),但标准 clojure 库中不存在此类宏。
  • defnk 在 clojure.contrib 中定义。它是在 Clojure 1.2 添加完整地图解构绑定之前创建的。 defnk 现在应该被认为是过时的(事实上,整体的 clojure.contrib 与未来的 Clojure 1.3 不兼容。)
  • 有没有办法使用 :do-logs 之类的关键字参数,然后在正文中使用 (when do-logs ...) 之类的东西?
猜你喜欢
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
相关资源
最近更新 更多