Arity and Variadic Functions
Explore arity concepts in Clojure by learning to create functions that accept different numbers of arguments, including variadic functions that handle any amount. Understand how to use techniques like apply and flatten to manipulate arguments and optimize function usage.
We'll cover the following...
The arity of a function is related to the number of arguments that the function accepts. So, for example, the function (sum-numbers a b) has an arity equal to 2 because it receives two values, a and b.
Multi-arity functions
In Clojure, as in many other programming languages, we can create functions with multiple possible arities, so the same function might receive one, two, or N arguments, depending on the declaration that we do. In other programming languages, this feature is also known as function overloading.
When we have multi-arity functions, we can make one overload call another, so we can use this technique to set default argument values. And as in any other feature in Clojure, we have parentheses to isolate each new arity.
Let’s see an example:
As we can see, the structure of a function with arities is the following: ...