Clojure 关键字参数
在 Common Lisp 中你可以这样做:
(defun foo (bar &key baz quux)
(list bar baz quux))
(foo 1 :quux 3 :baz 2) ; => (1 2 3)
Clojure 没有关键字参数。 一种替代方法是:
(defn foo [bar {:keys [baz quux]}]
(list bar baz quux))
(foo 1 {:quux 3 :baz 2}) ; => (1 2 3)
嵌套括号太多,必须一直键入和读取。 它还需要显式哈希映射作为参数而不是平面列表传入。
Clojure 中最惯用的关键字参数等效项是什么,看起来不会有人引爆标点符号炸弹?
In Common Lisp you can do this:
(defun foo (bar &key baz quux)
(list bar baz quux))
(foo 1 :quux 3 :baz 2) ; => (1 2 3)
Clojure doesn't have keyword arguments. One alternative is this:
(defn foo [bar {:keys [baz quux]}]
(list bar baz quux))
(foo 1 {:quux 3 :baz 2}) ; => (1 2 3)
That's too many nested brackets to have to type and read all the time. It also requires an explicit hash-map to be passed in as an argument rather than a flat list.
What's the most idiomatic Clojure equivalent of keyword arguments that doesn't look someone set off a punctuation bomb?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了更新 Clojure 1.2 的这个答案,现在有完整的关键字参数支持,以及 解构绑定< 的映射形式提供的默认值/a>:
To update this answer for Clojure 1.2 there is now full keyword arg support with defaults provided by the map forms of destructuring binding:
在 clojure 中模拟关键字参数的一个简单方法是在剩余参数上使用哈希映射,如下所示:
Rich Hickey 在 此消息来自 clojure google 群组,为您提供关键字参数。 相应帖子包含有关关键字参数为何如此的信息Clojure 不支持。 基本上是为了避免运行时开销。 Rich 解释了我在上面此消息中展示的方法
A simple way to simulate keyword args in clojure is using hash-map on rest parameters like this:
Rich Hickey provided a macro in this message from the clojure google group that gives you keyword parameters. The corresponding thread contains information about why keyword parameters are not supported by clojure. Basically to avoid the runtime overhead. Rich explains the method I've shown above in this message
clojure.contrib.def
最近添加了defnk
宏,它可以使用关键字参数定义函数(请参阅此处)。A recent addition to
clojure.contrib.def
is thedefnk
macro, which enables definition of functions with keyword arguments (see here).