有谁知道在Clojure中提供关键字参数的好方法?

Zub*_*air 5 clojure

我希望能够使用关键字参数调用clojure函数,如下所示:

(do-something :arg1 1 :arg2 "Hello")
Run Code Online (Sandbox Code Playgroud)

:这是可能的,而不必做:

(do-something {:arg1 1 :arg2 "Hello"})
Run Code Online (Sandbox Code Playgroud)

:我还可以使用:pre pre-conditions来提供somse类型的验证,以确保包含所有参数吗?

cem*_*ick 5

关键字args由rest args的内置解构提供(尽管主要的解构文档不包括1.2中的这个添加):

(defn foo
  [a b & {:keys [c d]}]
  [a b c d])
#'user/foo
(foo 1 2 :c 12 :d [1])
[1 2 12 [1]]
Run Code Online (Sandbox Code Playgroud)

所有常见的地图解构设施齐备(例如:or,:strs,:syms等).


Ral*_*lph 3

如果您想要关键字 args 的默认值,请执行以下操作 (Clojure 1.2):

(defn foo
  [req1 req2 & {:keys [opt1 opt2] :or {opt1 :hello opt2 :goodbye}}]
  [req1 req2 opt1 opt2])
#'user/foo
user=> (foo :a :b)
[:a :b :hello :goodbye]
user=> (foo :a :b :opt1 "xyz")
[:a :b "xyz" :goodbye]
Run Code Online (Sandbox Code Playgroud)