How to create default value for function argument in Clojure

jcubic picture jcubic · Jul 9, 2010 · Viewed 51.8k times · Source

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.

Answer

Brian Carper picture Brian Carper · Jul 9, 2010

A function can have multiple signatures if the signatures differ in arity. You can use that to supply default values.

(defn string->integer 
  ([s] (string->integer s 10))
  ([s base] (Integer/parseInt s base)))

Note that assuming false and nil are both considered non-values, (if (nil? base) 10 base) could be shortened to (if base base 10), or further to (or base 10).