I would like to be able to call clojure functions using keyword arguments like this:
(do-something :arg1 1 :arg2 "Hello")
: Is this possible without having to do:
(do-something {:arg1 1 :arg2 "Hello"})
: and could I also use :pre pre-conditions to provide somse sort of validation to make sure all arguments are included?
Keyword arguments can often be used to make function calls more explicit. This takes a file object output_file and contents string and writes a gzipped version of the string to the output file.
Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword.
Keyword arguments are passed to functions after any required positional arguments. But the order of one keyword argument compared to another keyword argument does not matter.
In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols: *args (Non Keyword Arguments) **kwargs (Keyword Arguments)
Keyword args are provided by the built-in destructuring of rest args (though the main docs for destructuring unfortunately doesn't cover this addition in 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]]
All of the usual map destructuring facilities are available (e.g. :or
, :strs
, :syms
, etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With