Clojure 关键字参数

发布于 2024-07-16 14:20:19 字数 422 浏览 7 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光清浅 2024-07-23 14:20:19

为了更新 Clojure 1.2 的这个答案,现在有完整的关键字参数支持,以及 解构绑定< 的映射形式提供的默认值/a>:

user> (defn foo [bar &{ :keys [baz quux] 
                        :or {baz "baz_default" quux "quux_default"}}]
         (list bar baz quux))
#'user/foo

user> (foo 1 :quux 3)
(1 "baz_default" 3)

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:

user> (defn foo [bar &{ :keys [baz quux] 
                        :or {baz "baz_default" quux "quux_default"}}]
         (list bar baz quux))
#'user/foo

user> (foo 1 :quux 3)
(1 "baz_default" 3)
水晶透心 2024-07-23 14:20:19

在 clojure 中模拟关键字参数的一个简单方法是在剩余参数上使用哈希映射,如下所示:

> (defn kwtest [x & e] (:foo (apply hash-map e)))
#'user/kwtest
> (kwtest 12 :bar "ignored" :foo "returned")
"returned"

Rich Hickey 在 此消息来自 clojure google 群组,为您提供关键字参数。 相应帖子包含有关关键字参数为何如此的信息Clojure 不支持。 基本上是为了避免运行时开销。 Rich 解释了我在上面此消息中展示的方法

A simple way to simulate keyword args in clojure is using hash-map on rest parameters like this:

> (defn kwtest [x & e] (:foo (apply hash-map e)))
#'user/kwtest
> (kwtest 12 :bar "ignored" :foo "returned")
"returned"

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

勿忘初心 2024-07-23 14:20:19

clojure.contrib.def 最近添加了 defnk 宏,它可以使用关键字参数定义函数(请参阅此处)。

A recent addition to clojure.contrib.def is the defnk macro, which enables definition of functions with keyword arguments (see here).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文