Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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?

like image 543
yazz.com Avatar asked Jan 04 '11 12:01

yazz.com


People also ask

What are some other uses for keyword arguments in functions?

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.

What are keyword arguments give example?

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.

Can we pass keyword arguments in any order?

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.

How do you pass a keyword argument in Python?

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)


1 Answers

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).

like image 145
cemerick Avatar answered Sep 29 '22 00:09

cemerick