Examples of Clojure arity-overloading on functions like the following (taken from the cookbook):
(defn argcount
([] 0) ; Zero arguments
([x] 1) ; One argument
([ x & args] (inc (count args)))) ; List of arguments
… use a form that doesn’t seem to allow the functions of lower arity to simply call the functions of higher arity with some default values (that’s a common idiom in Java).
Is some other special form used for that ?
There’s usually a good way to express the higher arity arguments in a way that doesn’t need to refer to other arities using higher order functions and
map/reduce. In this case it’s pretty simple:Notice the general form of the expression is:
You can’t do everything this way, but this works for a surprisingly large proportion of multi-argument functions. It also gains the advnatages of laziness using
map, so you can do crazy things like pass ten million arguments to a function with little fear:Try that in most other languages and your stack will be toast 🙂