liveBook · Manning

Arity

As explained in Elixir in Action, Third Edition

Arity is the number of arguments that a function receives.

Arity is the number of arguments a function receives. In Elixir, a function is identified by its module, name, and arity, so Rectangle.area/1 and Rectangle.area/2 are distinct functions. section 2.3.3

Different arities commonly provide a simple interface over a more general implementation: a lower-arity function delegates to a higher-arity function with default arguments. The \\ operator generates these arities automatically. Because arity distinguishes functions, Elixir does not support functions accepting a variable number of arguments. section 2.3.3

Delegating across arities

Rectangle.area(5) calls area/1 and returns 25; Rectangle.area(5, 6) calls area/2 and returns 30. Likewise, def add(a, b \\ 0), do: a + b provides add/1 and add/2. section 2.3.3

Listing 2.2 Functions with the same name but different arities (arity_demo.ex)
defmodule Rectangle do
  def area(a), do: area(a, a)    #1
 
  def area(a, b), do: a * b      #2
end

Inspect a compact implementation where area/1 delegates to area/2. section 2.3.3

How Elixir in Action, Third Edition covers it

How deep it goes
Explains function identity, delegation, generated arities, and the boundary against variable-argument functions.
Examples
Uses Rectangle.area, Calculator.add, Enum.each, and one-arity and three-arity lambdas.
What it assumes
Assumes basic function definitions and calls while establishing arity from simple examples.
What you can do after
Apply arity notation and default-argument definitions when designing and calling Elixir functions.
How it connects
Connects functions with default arguments, anonymous functions, function captures, and higher-order iteration.

Also explained in

Compare how 5 books explain arity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.