Clojure - named arguments

Viewed 21889

Does Clojure have named arguments? If so, can you please provide a small example of it?

4 Answers

As of Clojure version 1.8, keyword support still seems a bit meh.

You can specify keyword arguments like this:

(defn myfn1
  "Specifying keyword arguments without default values"
  [& {:keys [arg1 arg2]}]
  (list arg1 arg2))

Examples of calling it:

(myfn1 :arg1 23 :arg2 45)  --> evaluates to (23 45)
(myfn1 :arg1 22)           --> evaluates to (22 nil)

If you want to specify default values for these keyword arguments:

(defn myfn2
  "Another version, this time with default values specified"
  [& {:keys [arg1 arg2] :or {arg1 45 arg2 55}}]
  (list arg1 arg2))

This does the expected thing in the second case:

(myfn2 :arg1 22)           --> evaluates to (22 55)

There are pros and cons to each part of each language, but just for comparison, this is how you would do the same stuff in Common Lisp:

(defun myfn3
    (&key arg1 arg2)
    "Look Ma, keyword args!"
    (list arg1 arg2))

(defun myfn4
    (&key (arg1 45) (arg2 55))
    "Once again, with default values"
    (list arg1 arg2))
Related