Variadic Functions in Elixir
Here’s the example translated to Elixir:
Variadic functions can be called with any number of trailing arguments. For example, IO.puts
is a common variadic function.
Here’s a function that will take an arbitrary number of integers as arguments.
Within the function, the type of nums
is equivalent to a list of integers. We can call length(nums)
, iterate over it with Enum.each
, etc.
Variadic functions can be called in the usual way with individual arguments.
If you already have multiple arguments in a list, apply them to a variadic function like this:
To run the program, save the code in a file (e.g., example.exs
) and use elixir
to execute it.
Another key aspect of functions in Elixir is their ability to form closures, which we’ll look at next.
Next example: Closures.