Clojure - 命名参数 [英] Clojure - named arguments

查看:15
本文介绍了Clojure - 命名参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clojure 有命名参数吗?如果是这样,你能提供一个小例子吗?

Does Clojure have named arguments? If so, can you please provide a small example of it?

推荐答案

在 Clojure 1.2 中,您可以像解构地图一样解构 rest 参数.这意味着您可以使用命名的非位置关键字参数.下面是一个例子:

In Clojure 1.2, you can destructure the rest argument just like you would destructure a map. This means you can do named non-positional keyword arguments. Here is an example:

user> (defn blah [& {:keys [key1 key2 key3]}] (str key1 key2 key3))
#'user/blah
user> (blah :key1 "Hai" :key2 " there" :key3 10)
"Hai there10"
user> (blah :key1 "Hai" :key2 " there")
"Hai there"
user> (defn blah [& {:keys [key1 key2 key3] :as everything}] everything)
#'user/blah
user> (blah :key1 "Hai" :key2 " there")
{:key2 " there", :key1 "Hai"}

在解构 Clojure 映射时可以做的任何事情都可以在函数的参数列表中完成,如上所示.包括使用 :or 为参数定义默认值,如下所示:

Anything you can do while destructuring a Clojure map can be done in a function's argument list as shown above. Including using :or to define defaults for the arguments like this:

user> (defn blah [& {:keys [key1 key2 key3] :or {key3 10}}] (str key1 key2 key3))
#'user/blah
user> (blah :key1 "Hai" :key2 " there")
"Hai there10"

但这在 Clojure 1.2 中.或者,在旧版本中,您可以这样做来模拟相同的事情:

But this is in Clojure 1.2. Alternatively, in older versions, you can do this to simulate the same thing:

user> (defn blah [& rest] (let [{:keys [key1 key2 key3] :or {key3 10}} (apply hash-map rest)] (str key1 key2 key3)))
#'user/blah
user> (blah :key1 "Hai" :key2 " there")
"Hai there10"

通常以相同的方式工作.

and that works generally the same way.

并且您还可以在关键字参数之前使用位置参数:

And you can also have positional arguments that come before the keyword arguments:

user> (defn blah [x y & {:keys [key1 key2 key3] :or {key3 10}}] (str x y key1 key2 key3))
#'user/blah
user> (blah "x" "Y" :key1 "Hai" :key2 " there")
"xYHai there10"

这些不是可选的,必须提供.

These are not optional and have to be provided.

实际上,您可以像处理任何 Clojure 集合一样对 rest 参数进行解构.

You can actually destructure the rest argument like you would any Clojure collection.

user> (defn blah [& [one two & more]] (str one two "and the rest: " more))
#'user/blah
user> (blah 1 2 "ressssssst")
"12and the rest: ("ressssssst")"

您甚至可以在 Clojure 1.1 中执行此类操作.不过,关键字参数的映射式解构仅在 1.2 中出现.

You can do this sort of thing even in Clojure 1.1. The map-style destructuring for keyword arguments only came in 1.2 though.

这篇关于Clojure - 命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆