Multiple Return Values in Elixir

Elixir has built-in support for multiple return values. This feature is used often in idiomatic Elixir, for example to return both result and error values from a function.

defmodule MultipleReturnValues do
  # The tuple {integer, integer} in this function signature shows that
  # the function returns 2 integers.
  def vals do
    {3, 7}
  end

  def main do
    # Here we use pattern matching to get the 2 different return values
    # from the function call.
    {a, b} = vals()
    IO.puts(a)
    IO.puts(b)

    # If you only want a subset of the returned values,
    # use the underscore _ as a placeholder.
    {_, c} = vals()
    IO.puts(c)
  end
end

To run the program:

$ elixir multiple_return_values.exs
3
7
7

In Elixir, functions that return multiple values typically return them as tuples. Pattern matching is used to extract the values from the tuple. This is similar to multiple assignment in some other languages.

The underscore _ in Elixir serves a similar purpose to the blank identifier in some other languages. It’s used when you want to ignore a value in pattern matching.

Accepting a variable number of arguments is another nice feature of Elixir functions; we’ll look at this next.