Multi-variadic functions

We've mentioned that range has multiple arities. Such functions are called multi-variadic. This is how to define multiple arities in your own functions:

(defn area
  ([]  (* 3.14 1 1 ))
  ([r] (* 3.14 r r)))

Now area may be called with zero or one argument. When called with zero arguments area returns the area of a unit circle of radius 1:

user=> (area)
3.14

user=> (area 1)
3.14

user=> (area 2)
12.56

Of course, functions can call themselves, so instead of repeating the formula we could make a 1-arity call:

(defn area
  ([]  (area 1))
  ([r] (* 3.14 r r)))

It is also possible to define a function that accepts any number of arguments by putting a & symbol in the parameters list. The parameter that follows & will collect all remaining arguments as a sequence.

(defn glue [title name & rest]
  (str title " " name " and the friends " rest))

Exercise

Exercise 1. Recall function sphere-area-inc which you've created before. It increments the incoming radius value by 1, then calculates sphere surface area. Modify that function by adding a 2-arity. When called with 2 arguments r and a, sphere-area-inc should increment r by a before calculating the area.

user=> (sphere-area-inc 7)
615.44

user=> (sphere-area-inc 7 2)
1017.36

user=> (sphere-area-inc 8)
1017.36

user=> (sphere-area-inc 0)
12.56

user=> (sphere-area-inc 0 7)
615.44