DEV Community

Alex Cosmas
Alex Cosmas

Posted on

What is the -> arrow in Elixir

-> is a fundamental part of the Elixir syntax and plays several roles but first what is it.
The -> arrow is used to denote function clauses, as well as to define anonymous functions.

1. Defining Function Clauses
In pattern matching, the -> arrow separates the function head (which includes the function name and its arguments) from the function body.
For example:

defmodule Math do
  def sum(a, b) do
    a + b
  end
end
Enter fullscreen mode Exit fullscreen mode

Here, def sum(a, b) do ... end is a function clause, and the -> arrow is implied within the do ... end block.

Anonymous Functions
When creating anonymous functions using the fn keyword, the -> arrow separates the arguments and body of the function.
For example:

add = fn a, b -> a + b end
Enter fullscreen mode Exit fullscreen mode

In this case, fn a, b -> a + b end defines an anonymous function that takes a and b as arguments and returns their sum (a + b). The -> arrow separates the arguments from the function body.

The -> arrow is crucial for indicating the separation between the arguments and the function body in both function definitions and anonymous functions in Elixir.

Top comments (0)