Newbie: Optional parameters without multiple definitions

84 views
Skip to first unread message

samppi

unread,
Nov 15, 2008, 11:59:30 AM11/15/08
to Clojure
Is there a more concise way of expressing an optional parameter with a
default other than writing another entire definition?

That is, instead of:
(defn a-function ; two parameters, x and y, and y is 23 by default
([x] (a-function x 23)
([x y] ...))

...is it possible to do something like:
(defn a-function [x [y :default 3]
...)

I'm fine with the first way, but I'm just wondering if there's another
way.

Craig Andera

unread,
Nov 15, 2008, 12:33:35 PM11/15/08
to clo...@googlegroups.com
If you're cool with passing a map instead of plain parameters, you
could use destructuring to do this:

(defn test1 [{x :x, y :y, :or {:y 3}}]
[x y])

(test1 {:x 2}) => [2 3]

Another thing you could do would be to use variable arity and handle
the absence of the other parameters in the method body.

(defn test2 [x & y]
(let [y (or (first y) 23)]
[x y]))

If you wanted something more like CL, you could use a hash-map and merge

(defn test3 [& p]
(let [m (merge {:y 42} (hash-map p))
x (:x m)
y (:y m)]
[x y]))

(Although for some reason that is blowing up in my repl at the moment.
Hopefully the idea is clear enough.)

If you find yourself doing this a lot, it seems like this is one place
where macros could help you out, although I've not written enough Lisp
for real to know if this is one of those places where something
simpler will suffice.
Reply all
Reply to author
Forward
0 new messages