Search code examples
functionclojuredefault-valueoptional-parameters

How to create default value for function argument in Clojure


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.


Solution

  • 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).