Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure keyword arguments

In Common Lisp you can do this:

(defun foo (bar &key baz quux)   (list bar baz quux))  (foo 1 :quux 3 :baz 2) ; => (1 2 3) 

Clojure doesn't have keyword arguments. One alternative is this:

(defn foo [bar {:keys [baz quux]}]    (list bar baz quux))  (foo 1 {:quux 3 :baz 2}) ; => (1 2 3) 

That's too many nested brackets to have to type and read all the time. It also requires an explicit hash-map to be passed in as an argument rather than a flat list.

What's the most idiomatic Clojure equivalent of keyword arguments that doesn't look someone set off a punctuation bomb?

like image 361
Brian Carper Avatar asked Apr 04 '09 22:04

Brian Carper


1 Answers

To update this answer for Clojure 1.2 there is now full keyword arg support with defaults provided by the map forms of destructuring binding:

user> (defn foo [bar &{ :keys [baz quux]                          :or {baz "baz_default" quux "quux_default"}}]          (list bar baz quux)) #'user/foo  user> (foo 1 :quux 3) (1 "baz_default" 3) 
like image 93
Alex Stoddard Avatar answered Sep 21 '22 13:09

Alex Stoddard