I found it hard to figure out how best to get common lisp-style keyword
arguments with defaults, and had been doing it in a clunky way until Chas
showed me the way I show below. Now I've had a student also fail to figure it
out until I showed him, and it occurred to me that maybe I should suggest
adding this to the documentation (or adding it more prominently if it's already
there somewhere). Where? I don't know, but maybe it ought to be described both
in documentation for fn (http://clojure.org/special_forms#fn), since there's
already mention of & (rest) arguments there, and in places like clojuredocs.
I do realize that this is just a special case of let binding, but if it's a
good idiom for use in defn then it'd be nice for it to be more described more
conspicuously.
(defn foo
"This function takes arguments specified with keywords, with defaults."
[& {:keys [arg1 arg2 arg3]
:or {arg1 0
arg2 [0 1 2]
arg3 '(a b c)}}]
(println "Called with arg1 =" arg1 ", arg2 =" arg2 ", arg3 =" arg3))
(foo)
(foo :arg1 17)
(foo :arg2 17)
(foo :arg3 17)
(foo :arg3 100 :arg1 "hi!")
(foo :arg2 :funky! :arg3 100 :arg1 "hi!")
-Lee
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en