Clojure命名参数 [英] Clojure - named arguments
问题描述
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地图时执行的任何操作都可以在函数的参数列表中完成,如上所示。包括使用:或定义如下参数的默认值:
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 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"
b $ b
这些不是可选的,必须提供。
These are not optional and have to be provided.
你实际上可以解构 rest
user> (defn blah [& [one two & more]] (str one two "and the rest: " more))
#'user/blah
user> (blah 1 2 "ressssssst")
"12and the rest: (\"ressssssst\")"
b $ b
你可以做这种事情,即使在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屋!