Elixir Modules & Named Functions
Anonymous functions are handy, but most Elixir code lives in named functions grouped into modules. A module is defined with defmodule, and functions inside it with def (public) or defp (private).
defmodule Greeter do
def hello(name) do
"Hello, " <> name <> "!"
end
def shout(name), do: String.upcase(hello(name))
end
IO.puts(Greeter.hello("Ines"))
IO.puts(Greeter.shout("Ines"))Hello, Ines!
HELLO, INES!
- Module names are written in
CamelCaseand can be nested with dots:MyApp.Accounts.User. - Function names are
snake_case. A name ending in?returns a boolean (valid?/1), a name ending in!raises on failure instead of returning an error tuple (File.read!/1). def name(args), do: expris the one-line form;do ... endblocks are for longer bodies.- Named functions are called without a dot:
Greeter.hello("Ines"). Inside the module you can omit the module name.
The last expression of a function is its return value. There is no return keyword.
Public and private functions
defp defines a function that can only be called from inside its module. Use it for helpers that are not part of the module's API:
defmodule Price do
def with_vat(net, country), do: round2(net * (1 + rate(country)))
defp rate(:pt), do: 0.23
defp rate(:de), do: 0.19
defp rate(_other), do: 0.20
defp round2(x), do: Float.round(x, 2)
end
IO.inspect(Price.with_vat(100, :pt))
IO.inspect(Price.with_vat(19.99, :de))
IO.inspect(Price.with_vat(50, :fr))
try do
apply(Price, :rate, [:pt])
rescue
e in UndefinedFunctionError -> IO.puts(Exception.message(e))
end123.0
23.79
60.0
function Price.rate/1 is undefined or private
rate/1 has three clauses. Elixir tries them in order and runs the first whose pattern matches. The next lesson is all about clauses and guards. (apply/3 calls a function given as module, name and argument list; it is used here only to show what happens when a private function is called from outside.)
Arity: same name, different functions
Functions with the same name but a different number of arguments are completely separate functions. Area.of/1 and Area.of/2 below are unrelated as far as Elixir is concerned:
defmodule Area do
def of(side), do: side * side
def of(width, height), do: width * height
end
IO.inspect(Area.of(4))
IO.inspect(Area.of(4, 5))
IO.inspect(function_exported?(Area, :of, 1))
IO.inspect(function_exported?(Area, :of, 3))16
20
true
false
Default arguments
\\ gives an argument a default value. Elixir generates the smaller-arity versions for you:
defmodule Invoice do
def line(item, qty \\ 1, unit \\ "pcs") do
"#{qty} #{unit} #{item}"
end
end
IO.puts(Invoice.line("bolts"))
IO.puts(Invoice.line("bolts", 50))
IO.puts(Invoice.line("cable", 3, "m"))1 pcs bolts
50 pcs bolts
3 m cable
If a function with defaults has several clauses, declare the defaults once in a function head without a body: def line(item, qty \\ 1, unit \\ "pcs"), followed by the clauses.
Capturing named functions
To pass a named function to Enum and friends, capture it with &Module.name/arity:
defmodule Temp do
def to_fahrenheit(c), do: c * 9 / 5 + 32
end
IO.inspect(Enum.map([0, 20, 100], &Temp.to_fahrenheit/1))
convert = &Temp.to_fahrenheit/1
IO.inspect(convert.(37))[32.0, 68.0, 212.0]
98.6
Documentation
Modules and functions are documented with @moduledoc and @doc. The text is available in IEx (h Temp.to_fahrenheit) and in generated HTML docs (ExDoc):
defmodule Temp do
@moduledoc "Temperature conversions."
@doc """
Converts Celsius to Fahrenheit.
iex> Temp.to_fahrenheit(100)
212.0
"""
def to_fahrenheit(c), do: c * 9 / 5 + 32
endThe iex> lines inside @doc can be run as tests with ExUnit's doctest.
Common mistakes
- Calling a named function with a dot:
Greeter.hello.("x")is wrong;Greeter.hello("x")is right. - Defining functions outside a module: in a
.exsscript,defmust still be insidedefmodule. - Assuming
defblocks see outer variables: named functions do not capture variables from outside the module, unlikefn.
Test yourself
What does defp define?
- A function that can be called from any module
- A function only callable inside its own module
- A protocol
- A macro
Are Shape.area/1 and Shape.area/2 the same function?
- Yes, the second argument is optional
- No, functions are identified by name and arity
- Only if the second argument has a default
- Defining both is a compile error
How do you pass String.trim/1 to Enum.map?
Enum.map(list, String.trim)Enum.map(list, &String.trim/1)Enum.map(list, String.trim/1)Enum.map(list, :String.trim)