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.
defmodule Example do
def sum(nums) do
IO.inspect(nums)
total = Enum.reduce(nums, 0, fn num, acc -> num + acc end)
IO.puts(total)
end
end
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.
Example.sum([1, 2])
Example.sum([1, 2, 3])
If you already have multiple arguments in a list, apply them to a variadic function like this:
nums = [1, 2, 3, 4]
Example.sum(nums)
To run the program, save the code in a file (e.g., example.exs
) and use elixir
to execute it.
$ elixir example.exs
[1, 2]
3
[1, 2, 3]
6
[1, 2, 3, 4]
10
Another key aspect of functions in Elixir is their ability to form closures, which we’ll look at next.
Next example: Closures.