1
votes

New to Elixir, trying to understand what this syntax means:

MyApplication.Module.function/2

What does the number after the function represent?

2

2 Answers

4
votes

The number represents the arity of the function. This syntax is used when you want to pass a named function to functions that take a function as an argument. It is real handy for things like

"1 2 3" |> String.split(" ") |> Enum.map(&String.to_integer/1)
1
votes

In Elixir and Erlang functions can have multiple body clauses (in contrast to C++, Java etc.), so to distinguish we use arity, where it's simply number of arguments.

For example:

defmodule Math do

  def sum(x) do
    x + 0
  end

  def sum(x, y) do
    x + y
  end
end

So in this you have two similar yet different functions: sum/1 and sum/2.

Quite often you can see that the function with larger number of arguments is used internally to calculcate the result.