Does anyone know a good way to provide keyword arguments in Clojure?

I would like to be able to call clojure functions using keyword arguments as follows:

(do-something :arg1 1 :arg2 "Hello")

: Is this possible without the need:

(do-something {:arg1 1 :arg2 "Hello"})

: and can I use: preconditions to provide a somse kind of check to make sure all arguments are included?

+5
source share
2 answers

If you want the default values ​​for args arguments, follow these steps (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]
+3
source

( , , 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]]

(, :or, :strs, :syms ..).

+5

All Articles