Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 48 ยท Core Language

Functions and Modules

Learn how to define Elixir functions inside modules with def and defp, use anonymous functions and the capture operator, arity, defaults and attributes.

Functions are the building blocks of Elixir programs, and modules are how you group them. There are no classes and no methods attached to objects: you write a module that holds related functions, and you call them with the module's name. Data and behavior stay separate, and the functions simply take values in and return new values out, as described in Immutability and Rebinding.

This lesson covers named functions, anonymous functions, the capture operator, arity, default arguments and module attributes. Elixir does not run on this site, so most examples are read-only, with JavaScript stand-ins that model the rules. The stand-ins are not real Elixir.

Modules and named functions

Named functions always live inside a module:

ELIXIR
defmodule Geometry do
  def area(width, height) do
    width * height
  end

  def perimeter(width, height), do: 2 * (width + height)
end

Geometry.area(3, 4)        # 12
Geometry.perimeter(3, 4)   # 14

def defines a public function, callable from other modules. The do ... end form suits several lines, while , do: is a one-line shorthand. A function returns the value of its last expression. There is no return keyword.

Module names are written in CamelCase and are really atoms (Geometry is :"Elixir.Geometry"). Nested names such as MyApp.Billing.Invoice are common and just a naming convention, not an actual hierarchy.

Private functions

defp defines a private function that only the same module can call. Use it for helpers, so the public surface of the module stays small:

ELIXIR
defmodule Greeter do
  def hello(name), do: build(name) <> "!"

  defp build(name), do: "Hello, " <> String.capitalize(name)
end

Greeter.hello("ana")     # "Hello, Ana!"
Greeter.build("ana")     # ** (UndefinedFunctionError) function Greeter.build/1 is undefined or private

Arity: the number of arguments

A function is identified by its name and arity (how many arguments it takes). Elixir writes this as name/arity. Geometry.area/2 and a hypothetical Geometry.area/1 would be two different functions that happen to share a name:

ELIXIR
defmodule Shape do
  def area(side), do: side * side
  def area(width, height), do: width * height
end

Shape.area(3)      # 9
Shape.area(3, 4)   # 12

This notation shows up in docs, error messages and the capture operator below. The Enum.map/2 function takes two arguments, for instance.

Default arguments

Put \\ after a parameter to give it a default:

ELIXIR
defmodule Greeting do
  def hello(name, greeting \\ "Hello") do
    "#{greeting}, #{name}!"
  end
end

Greeting.hello("Ana")            # "Hello, Ana!"
Greeting.hello("Ana", "Hi")      # "Hi, Ana!"

Behind the scenes Elixir generates hello/1 that calls hello/2 with the default. If a function has several clauses (Multiple Clauses and Guards), declare the defaults in a separate function head, a line without a body, so they are written once.

Anonymous functions

An anonymous function is created with fn and called with a dot and parentheses:

ELIXIR
add = fn a, b -> a + b end

add.(1, 2)        # 3
is_function(add)  # true

The dot is required because add is a variable that holds a function; the plain add(1, 2) would look for a named function. Anonymous functions can have several clauses, each with its own pattern, and they are closures: they remember the values of the variables around them when they were created.

ELIXIR
sign = fn
  0 -> :zero
  n when n > 0 -> :positive
  _ -> :negative
end

sign.(-4)   # :negative

The capture operator

The & operator turns an existing function into a value, or writes a short anonymous function:

ELIXIR
String.upcase("ana")                       # "ANA"
Enum.map(["ana", "ben"], &String.upcase/1) # ["ANA", "BEN"]

Enum.map([1, 2, 3], &(&1 * 10))            # [10, 20, 30]
Enum.map([1, 2, 3], fn n -> n * 10 end)    # the same, written long

&String.upcase/1 captures a named function by name and arity. In &(&1 * 10), &1 stands for the first argument, &2 for the second, and so on. Use it for short, obvious bodies. When the logic needs a name or more than one line, a regular fn is easier to read. You cannot nest one & capture inside another.

Module attributes

An attribute starts with @ and is evaluated while the module is compiled. It is commonly used for constants and documentation:

ELIXIR
defmodule Circle do
  @moduledoc "Circle maths."
  @pi 3.14159

  @doc "Area of a circle with the given radius."
  def area(radius), do: @pi * radius * radius
end

Circle.area(2)   # 12.56636

@moduledoc and @doc feed the documentation tools (see Typespecs, Dialyzer and Documentation). An attribute like @pi is inlined where it is read; it is not a variable you can change at runtime.

Using other modules

Three directives bring another module into reach, all lexically scoped:

ELIXIR
defmodule Report do
  alias MyApp.Billing.Invoice   # now write Invoice instead of the full name
  import Enum, only: [map: 2]   # call map/2 without the Enum. prefix
  require Logger                # needed to use Logger's macros
end

Prefer alias for readability and use import sparingly with only:, since a long list of unprefixed functions makes it unclear where each came from.

JavaScript stand-ins

The first stand-in models a module as an object and shows that a function is identified by name and arity, including how a default argument generates the lower arity.

JS Name and arity, defaults (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in shows closures and capture-style helpers. In JavaScript, arrow functions do the work of fn and &. Notice that the closure keeps the value it saw at creation, which is the Elixir behavior for rebinding.

JS Closures and capture (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Shape.area/2 mean?

    name/arity identifies a function by its name and how many arguments it takes.
  2. 2. How do you call an anonymous function stored in add?

    Anonymous functions are called with a dot before the parentheses: add.(1, 2).
  3. 3. What does defp do?

    defp creates a private function. Calling it from another module raises UndefinedFunctionError.
  4. 4. What is &(&1 + 1)?

    The & operator builds a short anonymous function, and &1 refers to the first argument.
  5. 5. What does a function return when it has no return statement?

    Elixir has no return keyword; the value of the last expression in the body is the result.

Summary

  • Named functions live in modules: def is public, defp is private, and the last expression is the result.
  • A function is identified by name and arity, written name/arity.
  • Default arguments use \\ and generate the lower arities for you.
  • Anonymous functions use fn ... end and are called with .(); they are closures.
  • &Mod.fun/arity captures a named function and &(&1 * 2) writes a short one.
  • Module attributes such as @moduledoc and @pi are set at compile time; alias, import and require bring other modules into reach.

Next up: Multiple Clauses and Guards.