Alex Rivera | Logout

How to create default value for function argument in Clojure

Asked 2010-07-08T22:01:37.033
147

I come with this:

(defn string->integer [str & [base]]
  (Integer/parseInt str (if (nil? base) 10 base)))

(string->integer "10")
(string->integer "FF" 16)

But it must be a better way to do this.

Edit
Report

1 Answer

176

You can also destructure rest arguments as a map since Clojure 1.2 [ref]. This lets you name and provide defaults for function arguments:

(defn string->integer [s & {:keys [base] :or {base 10}}]
    (Integer/parseInt s base))

Now you can call

(string->integer "11")
=> 11

or

(string->integer "11" :base 8)
=> 9

You can see this in action here: https://github.com/Raynes/clavatar/blob/master/src/clavatar/core.clj (for example)

answered 2011-12-28T20:21:23.057

Your Answer