steve....@gmail.com wrote:
> I am really enjoying learning Clojure. Great language! I'm curious:
> does Clojure have named arguments or default argument values, as in
> Common Lisp?
You may have noticed that functions in Clojure can be "overloaded" with
varying argument numbers. So you can simulate default argument values
like so:
(defn foo
([bar]
(prn bar))
([]
(foo "foo")))
Here, I'm defining a version of the function with one argument, and one
with no arguments, and the version with no arguments calls the 1-ary
function with a (default) built-in value.
I guess it's not as compact as explicit default arguments, but probably
more powerful.
As for named arguments, you could apply a Ruby-ism and use maps, for
which there is compact reader syntax:
(my-fn arg1 arg2 { :argname arg3 :argname2 arg4 })
Within the function, you could merge that map argument with a map of the
default values, the values set by the user overriding defaults:
(let [default-args { :a 12 :b 25 :c -1 } ]
(defn foo [argmap]
(let [args (merge default-args argmap)]
; use args here: (args :a), (args :b), etc.
)))
(foo { :b 5 }) ; just like calling (foo { :a 12 :b 5 :c -1 })
The aesthetics of that are probably debatable.
~phil
> As for named arguments, you could apply a Ruby-ism and use maps, for
> which there is compact reader syntax:
>
> (my-fn arg1 arg2 { :argname arg3 :argname2 arg4 })
>
> Within the function, you could merge that map argument with a map of the
> default values, the values set by the user overriding defaults:
>
> (let [default-args { :a 12 :b 25 :c -1 } ]
> (defn foo [argmap]
> (let [args (merge default-args argmap)]
> ; use args here: (args :a), (args :b), etc.
> )))
>
> (foo { :b 5 }) ; just like calling (foo { :a 12 :b 5 :c -1 })
>
> The aesthetics of that are probably debatable.
>
You could also use destructuring to ease the pain:
(defn foo [{a :a b :b c :c :or {a 12 b 25 c -1}}]
[a b c])
or better, thanks to Chouser, when symbols match keywords:
(defn foo [{:keys [a b c] :or {a 12 b 25 c -1}}]
[a b c])
(there are also shorthands for strings and symbols: replace :keys by
:strs or :syms)
Christophe