Kernel - Elixir v1.12.3
Kernel - Elixir v1.12.3
You can invoke Kernel functions and macros anywhere in Elixir code
without the use of the Kernel. prefix since they have all been automatically
imported. For example, in IEx, you can call:
iex> is_number(13)
true
If you don't want to import a function or macro from Kernel , use the
:except option and then list the function/macro by arity:
Elixir also has special forms that are always imported and cannot be skipped.
These are described in Kernel.SpecialForms .
Built-in types
The following modules handle Elixir built-in data types:
Atom - literal constants with a name ( true , false , and nil are atoms)
Float - numbers with floating point precision
Function - a reference to code chunk, created with the fn/1 special
form
Integer - whole numbers (not fractions)
List - collections of a variable number of elements (linked lists)
Map - collections of key-value pairs
Process - light-weight threads of execution
Port - mechanisms to interact with the external world
Tuple - collections of a fixed number of elements
Data types
Elixir also provides other data types that are built on top of the types listed
above. Some of them are:
Protocols
Protocols add polymorphic dispatch to Elixir. They are contracts
implementable by data types. See Protocol for more information on
protocols. Elixir provides the following protocols in the standard library:
Guards
This module includes the built-in guards used by Elixir developers. They are
a predefined set of functions and macros that augment pattern matching,
typically invoked after the when operator. For example:
The clause above will only be invoked if the user's age is more than or equal
to 16. Guards also support joining multiple conditions with and and or . The
whole guard is true if all guard expressions will evaluate to true . A more
complete introduction to guards is available in the Patterns and guards page.
Structural comparison
The comparison functions in this module perform structural comparison.
This means structures are compared based on their representation and not
on their semantic value. This is specially important for functions that are
meant to provide ordering, such as >/2 , </2 , >=/2 , <=/2 , min/2 , and
max/2 . For example:
will return true because structural comparison compares the :day field
before :month or :year . Therefore, when comparing structs, you often use
the compare/2 function made available by the structs modules themselves:
Alternatively, you can use the functions in the Enum module to sort or
compute a maximum/minimum:
Elixir has functions, like and/2 , that only work with booleans, but also
functions that work with these truthy/falsy values, like &&/2 and !/1 .
Examples
We can check the truthiness of a value by using the !/1 function twice.
Truthy values:
iex> !!true
true
iex> !!5
true
iex> !![1,2]
true
iex> !!"foo"
true
iex> !!false
false
iex> !!nil
false
Inlining
Some of the functions described in this module are inlined by the Elixir
compiler into their Erlang counterparts in the :erlang module. Those
functions are called BIFs (built-in internal functions) in Erlang-land and
they exhibit interesting properties, as some of them are allowed in guards
and others are used for compiler optimizations.
Most of the inlined functions can be seen in effect when capturing the
function:
iex> &Kernel.is_atom/1
&:erlang.is_atom/1
Summary
Guards
left * right
Arithmetic multiplication operator.
+value
Arithmetic positive unary operator.
left + right
Arithmetic addition operator.
-value
Arithmetic negative unary operator.
left - right
Arithmetic subtraction operator.
left / right
Arithmetic division operator.
left != right
Not equal to operator.
left == right
Equal to operator. Returns true if the two terms are equal.
abs(number)
Returns an integer or float which is the arithmetical absolute value of
number .
bit_size
bit_size(bitstring)
Returns an integer which is the size in bits of bitstring .
byte_size(bitstring)
Returns the number of bytes needed to contain bitstring .
ceil(number)
Returns the smallest integer greater than or equal to number .
div(dividend, divisor)
Performs an integer division.
elem(tuple, index)
Gets the element at the zero-based index in tuple .
floor(number)
Returns the largest integer smaller than or equal to number .
hd(list)
Returns the head of a list. Raises ArgumentError if the list is empty.
left in right
Membership operator. Checks if the element on the left-hand side is a
member of the collection on the right-hand side.
is_atom(term)
Returns true if term is an atom; otherwise returns false .
is_binary(term)
Returns true if term is a binary; otherwise returns false .
is_bitstring(term)
Returns true if term is a bitstring (including a binary); otherwise returns
false .
is_boolean(term)
Returns true if term is either the atom true or the atom false (i.e., a
boolean); otherwise returns false .
is_exception(term)
Returns true if term is an exception; otherwise returns false .
is_exception(term, name)
Returns true if term is an exception of name ; otherwise returns false .
is_float(term)
Returns true if term is a floating-point number; otherwise returns false .
is_function(term)
Returns true if term is a function; otherwise returns false .
is_function(term, arity)
Returns true if term is a function that can be applied with arity number
of arguments; otherwise returns false .
is_integer(term)
Returns true if term is an integer; otherwise returns false .
is_list(term)
Returns true if term is a list with zero or more elements; otherwise returns
false .
is_map(term)
Returns true if term is a map; otherwise returns false .
is_map_key(map, key)
Returns true if key is a key in map ; otherwise returns false .
is_nil(term)
Returns true if term is nil , false otherwise.
is_number(term)
Returns true if term is either an integer or a floating-point number;
otherwise returns false .
is_pid(term)
Returns true if term is a PID (process identifier); otherwise returns false .
is_port(term)
Returns true if term is a port identifier; otherwise returns false .
is_reference(term)
Returns true if term is a reference; otherwise returns false .
is_struct(term)
Returns true if term is a struct; otherwise returns false .
is_struct(term, name)
Returns true if term is a struct of name ; otherwise returns false .
is_tuple(term)
Returns true if term is a tuple; otherwise returns false .
length(list)
Returns the length of list .
map_size(map)
Returns the size of a map.
node()
Returns an atom representing the name of the local node. If the node is not
alive, :nonode@nohost is returned instead.
node(arg)
Returns the node where the given argument is located. The argument can be
a PID, a reference, or a port. If the local node is not alive, :nonode@nohost is
returned.
not(value)
Strictly boolean "not" operator.
left or right
Strictly boolean "or" operator.
rem(dividend, divisor)
Computes the remainder of an integer division.
round(number)
Rounds a number to the nearest integer.
self()
Returns the PID (process identifier) of the calling process.
tl(list)
Returns the tail of a list. Raises ArgumentError if the list is empty.
trunc(number)
Returns the integer part of number .
tuple_size(tuple)
Returns the size of a tuple.
Functions
left && right
Boolean "and" operator.
left ++ right
List concatenation operator. Concatenates a proper list and a term,
returning a list.
left -- right
List subtraction operator. Removes the first occurrence of an element on the
left list for each element on the right.
first..last
Creates a range from first to last .
first..last//step
Creates a range from first to last with step .
!value
Boolean "not" operator.
left =~ right
Text-based match operator. Matches the term on the left against the
regular expression or string on the right .
@expr
Module attribute unary operator.
alias!(alias)
When used inside quoting, marks that the given alias should not be
hygienized. This means the alias will be expanded when the macro is
expanded.
apply(fun, args)
Invokes the given anonymous function fun with the list of arguments args .
binding(context \\ nil)
Returns the binding for the given context as a keyword list.
defdelegate(funs, opts)
Defines a function that delegates to another module.
defexception(fields)
Defines an exception.
defguard(guard)
Generates a macro suitable for use in guard expressions.
defguardp(guard)
Generates a private macro suitable for use in guard expressions.
defmodule(alias, do_block)
Defines a module given by name with the given contents.
defoverridable(keywords_or_behaviour)
Makes the given functions in the current module overridable.
defprotocol(name, do_block)
Defines a protocol.
defstruct(fields)
Defines a struct.
destructure(left, right)
Destructures two lists, assigning each term in the right one to the matching
term in the left one.
exit(reason)
Stops the execution of the calling process with the given reason.
get_and_update_in(path, fun)
Gets a value and updates a nested data structure via the given path .
get_in(data, keys)
Gets a value from a nested structure.
if(condition, clauses)
Provides an if/2 macro.
inspect(term, opts \\ [])
Inspects the given argument according to the Inspect protocol. The second
argument is a keyword list with options to control inspection.
make_ref()
Returns an almost unique reference.
match?(pattern, expr)
A convenience macro that checks if the right side (an expression) matches
the left side (a pattern).
max(first, second)
Returns the biggest of the two given terms according to their structural
comparison.
min(first, second)
Returns the smallest of the two given terms according to their structural
comparison.
pop_in(path)
Pops a key from the nested structure via the given path .
pop_in(data, keys)
Pops a key from the given nested structure.
put_in(path, value)
Puts a value in a nested structure via the given path .
raise(message)
Raises an exception.
raise(exception, attributes)
Raises an exception.
reraise(message, stacktrace)
Raises an exception preserving a previous stacktrace.
reraise(exception, attributes, stacktrace)
Raises an exception preserving a previous stacktrace.
send(dest, message)
Sends a message to the given dest and returns the message.
sigil_C(term, modifiers)
Handles the sigil ~C for charlists.
sigil_c(term, modifiers)
Handles the sigil ~c for charlists.
sigil_D(date_string, modifiers)
Handles the sigil ~D for dates.
sigil_N(naive_datetime_string, modifiers)
Handles the sigil ~N for naive date times.
sigil_R(term, modifiers)
Handles the sigil ~R for regular expressions.
sigil_r(term, modifiers)
Handles the sigil ~r for regular expressions.
sigil_S(term, modifiers)
Handles the sigil ~S for strings.
sigil_s(term, modifiers)
Handles the sigil ~s for strings.
sigil_T(time_string, modifiers)
Handles the sigil ~T for times.
sigil_U(datetime_string, modifiers)
Handles the sigil ~U to create a UTC DateTime .
sigil_W(term, modifiers)
Handles the sigil ~W for list of words.
sigil_w(term, modifiers)
Handles the sigil ~w for list of words.
spawn(fun)
Spawns the given function and returns its PID.
spawn_monitor(fun)
Spawns the given function, monitors it and returns its PID and monitoring
reference.
tap(value, fun)
Pipes value to the given fun and returns the value itself.
then(value, fun)
Pipes value into the given fun .
throw(term)
A non-local return from a function.
to_charlist(term)
Converts the given term to a charlist according to the List.Chars protocol.
to_string(term)
Converts the argument to a string according to the String.Chars protocol.
unless(condition, clauses)
Provides an unless macro.
update_in(path, fun)
Updates a nested structure via the given path .
left || right
Boolean "or" operator.
Guards
left * right
Examples
iex> 1 * 2
2
+value
Examples
iex> +1
1
left + right
Examples
iex> 1 + 2
3
-value
@spec -0 :: 0
@spec -pos_integer() :: neg_integer()
@spec -neg_integer() :: pos_integer()
@spec -float() :: float()
Examples
iex> -2
-2
left - right
Examples
iex> 1 - 2
-1
left / right
The result is always a float. Use div/2 and rem/2 if you want an integer
division or the remainder.
Examples
1 / 2
#=> 0.5
-3.0 / 2.0
#=> -1.5
5 / 1
#=> 5.0
7 / 0
** (ArithmeticError) bad argument in arithmetic expression
left != right
This operator considers 1 and 1.0 to be equal. For match comparison, use
!==/2 instead.
Examples
iex> 1 != 2
true
iex> 1 != 1.0
false
Returns true if the two terms are not exactly equal. See ===/2 for a
definition of what is considered "exactly equal".
Examples
iex> 1 !== 2
true
Less-than operator.
Examples
iex> 1 < 2
true
Examples
iex> 1 <= 2
true
left == right
This operator considers 1 and 1.0 to be equal. For stricter semantics, use
===/2 instead.
Examples
iex> 1 == 2
false
iex> 1 == 1.0
true
The terms are only considered to be exactly equal if they have the same
value and are of the same type. For example, 1 == 1.0 returns true , but
since they are of different types, 1 === 1.0 returns false .
Examples
iex> 1 === 2
false
Greater-than operator.
Examples
iex> 1 > 2
false
Examples
iex> 1 >= 2
false
abs(number)
Examples
iex> abs(-3.33)
3.33
iex> abs(-3)
3
Examples
iex> true and false
false
Extracts the part of the binary starting at start with length length .
Binaries are zero-indexed.
Examples
iex> binary_part("foo", 1, 2)
"oo"
A negative length can be used to extract bytes that come before the byte at
start :
binary_part("Hello", 0, 10)
** (ArgumentError) argument error
bit_size
bit_size(bitstring)
@spec bit_size(
bit_size bitstring()) :: non_neg_integer()
Examples
iex> bit_size
bit_size(<<433::16, 3::3>>)
19
iex> bit_size
bit_size(<<1, 2, 3>>)
24
byte_size(bitstring)
Examples
div(dividend, divisor)
div/2 performs truncated integer division. This means that the result is
always rounded towards zero.
Examples
div(5, 2)
#=> 2
div(6, -4)
#=> -1
div(-99, 2)
#=> -49
div(100, 0)
** (ArithmeticError) bad argument in arithmetic expression
elem(tuple, index)
Examples
elem({}, 0)
** (ArgumentError) argument error
elem({:foo, :bar}, 2)
** (ArgumentError) argument error
hd(list)
Examples
hd([1, 2, 3, 4])
#=> 1
hd([1 | 2])
#=> 1
tl([])
#=> ** (ArgumentError) argument error
Examples
iex> x = 1
iex> x in [1, 2, 3]
true
Enum.member?([1, 2, 3], x)
iex> x = 1
iex> x not in [1, 2, 3]
false
Guards
The in/2 operator (as well as not in ) can be used in guard clauses as
long as the right-hand side is a range or a list. In such cases, Elixir will
expand the operator to a valid guard expression. For example:
when x in [1, 2, 3]
translates to:
when x in 1..3
translates to:
AST considerations
is_atom(term)
Examples
iex> is_binary("foo")
true
iex> is_binary(<<1::3>>)
false
is_bitstring(term)
Examples
iex> is_bitstring("foo")
true
iex> is_bitstring(<<1::3>>)
true
is_boolean(term)
Returns true if term is either the atom true or the atom false (i.e., a
boolean); otherwise returns false .
Allowed in guard tests. Inlined by the compiler.
Examples
iex> is_exception(%RuntimeError{})
true
iex> is_exception(%{})
false
Examples
is_float(term)
is_function(term, arity)
Returns true if term is a function that can be applied with arity number
of arguments; otherwise returns false .
Examples
is_integer(term)
is_list(term)
is_map(term)
is_nil(term) (macro)
Examples
iex> is_nil(1)
false
iex> is_nil(nil)
true
is_number(term)
is_pid(term)
is_port(term)
is_reference(term)
Examples
iex> is_struct(URI.parse("/"))
true
iex> is_struct(%{})
false
Examples
is_tuple(term)
length(list)
Examples
iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9])
9
map_size(map)
The size of a map is the number of key-value pairs that the map contains.
Examples
node()
Returns an atom representing the name of the local node. If the node is
not alive, :nonode@nohost is returned instead.
node(arg)
Returns the node where the given argument is located. The argument can
be a PID, a reference, or a port. If the local node is not alive,
:nonode@nohost is returned.
Examples
Examples
iex> false or 42
42
iex> 42 or false
** (BadBooleanError) expected a boolean on left-side of "or", got:
42
rem(dividend, divisor)
rem/2 uses truncated division, which means that the result will always
have the sign of the dividend .
Examples
iex> rem(5, 2)
1
iex> rem(6, -4)
2
round(number)
Examples
iex> round(5.6)
6
iex> round(5.2)
5
iex> round(-9.9)
-10
iex> round(-9)
-9
iex> round(2.5)
3
iex> round(-2.5)
-3
self()
tl(list)
Examples
tl([1, 2, 3, :go])
#=> [2, 3, :go]
tl([:one])
#=> []
tl([:a, :b | :c])
#=> [:b | :c]
tl([])
#=> ** (ArgumentError) argument error
trunc(number)
Examples
iex> trunc(5.4)
5
iex> trunc(-5.99)
-5
iex> trunc(-5)
-5
tuple_size(tuple)
Examples
Functions
Examples
Note that, unlike and/2 , this operator accepts any expression as the first
argument, not only booleans.
left ++ right
If the right operand is not a proper list, it returns an improper list. If the
left operand is not a proper list, it raises ArgumentError .
Examples
left -- right
Examples
As it is equivalent to:
first..last (macro)
If first is less than last, the range will be increasing from first to last. If
first is equal to last, the range will contain one element, which is the
number itself.
If first is more than last, the range will be decreasing from first to last,
albeit this behaviour is deprecated. Instead prefer to explicitly list the step
with first..last//-1 .
Examples
iex> 0 in 1..3
false
iex> 2 in 1..3
true
iex> Enum.to_list(1..3)
[1, 2, 3]
Examples
iex> 0 in 1..3//1
false
iex> 2 in 1..3//1
true
iex> 2 in 1..3//2
false
iex> Enum.to_list(1..3//1)
[1, 2, 3]
iex> Enum.to_list(1..3//2)
[1, 3]
iex> Enum.to_list(3..1//-1)
[3, 2, 1]
iex> Enum.to_list(1..0//1)
[]
!value (macro)
Receives any value (not just booleans) and returns true if value is false
or nil ; returns false otherwise.
Examples
iex> !Enum.empty?([])
false
iex> !List.first([])
true
Examples
The <>/2 operator can also be used in pattern matching (and guard
clauses) as long as the left argument is a literal binary:
left =~ right
@spec String.t() =~ (String.t() | Regex.t()) :: boolean()
Text-based match operator. Matches the term on the left against the
regular expression or string on the right .
Examples
@expr (macro)
defmodule MyServer do
@my_data 13
IO.inspect(@my_data)
#=> 13
end
Unlike Erlang, such attributes are not stored in the module by default
since it is common in Elixir to use custom attributes to store temporary
data that will be available at compile-time. Custom attributes may be
configured to behave closer to Erlang by using
Module.register_attribute/3 .
defmodule MyServer do
@my_data 11
def first_data, do: @my_data
@my_data 13
def second_data, do: @my_data
end
MyServer.first_data()
#=> 11
MyServer.second_data()
#=> 13
While the above is fine, imagine if instead you have actual module names
in the module attribute, like this:
alias!(alias) (macro)
When used inside quoting, marks that the given alias should not be
hygienized. This means the alias will be expanded when the macro is
expanded.
Invokes the given anonymous function fun with the list of arguments
args .
Examples
Invokes the given function from module with the list of arguments args .
If the number of arguments and the function name are known at compile
time, prefer module.function(arg_1, arg_2, ..., arg_n) as it is clearer
than apply(module, :function, [arg_1, arg_2, ..., arg_n]) .
Examples
In the returned result, keys are variable names and values are the
corresponding variable values.
If the given context is nil (by default it is), the binding for the current
context is returned.
Examples
iex> x = 1
iex> binding()
[x: 1]
iex> x = 2
iex> binding()
[x: 2]
iex> binding(:foo)
[]
iex> var!(x, :foo) = 1
1
iex> binding(:foo)
[x: 1]
Examples
defmodule Foo do
def bar, do: :baz
end
Foo.bar()
#=> :baz
Default arguments
defmodule MyMath do
def multiply_by(number, factor \\ 2) do
number * factor
end
end
MyMath.multiply_by(4, 3)
#=> 12
MyMath.multiply_by(4)
#=> 8
The compiler translates this into multiple functions with different arities,
here MyMath.multiply_by/1 and MyMath.multiply_by/2 , that represent cases
when arguments for parameters with default values are passed or not
passed.
Note that \\ can't be used with anonymous functions because they can
only have a sole arity.
defmodule MyConfiguration do
end
The difference between using Map and Keyword to store many arguments
is Keyword 's keys:
must be atoms
can be given more than once
ordered, as specified by the developer
def foo(bar) do
[]
end
#=> warning: variable bar is unused
def foo(_bar) do
[]
end
#=> no warning
def foo(_bar) do
_bar
end
#=> warning: the underscored variable "_bar" is used after being set
def convert(number) do
String.to_integer(number)
rescue
e in ArgumentError -> {:error, e.message}
end
Functions defined with defdelegate/2 are public and can be invoked from
outside the module they're defined in, as if they were defined using
def/2 . Therefore, defdelegate/2 is about extending the current module's
public API. If what you want is to invoke a function defined in another
module without using its full module name, then use alias/2 to shorten
the module name or use import/2 to be able to invoke the function
without the module name altogether.
Options
:as - the function to call on the target given in :to . This parameter
is optional and defaults to the name being delegated ( funs ).
Examples
defmodule MyList do
defdelegate reverse(list), to: Enum
defdelegate other_reverse(list), to: Enum, as: :reverse
end
MyList.reverse([1, 2, 3])
#=> [3, 2, 1]
MyList.other_reverse([1, 2, 3])
#=> [3, 2, 1]
defexception(fields) (macro)
Defines an exception.
Raising exceptions
value = [:hello]
raise MyAppError,
message: "did not get what was expected, got: #{inspect(value)}"
defmodule MyAppError do
defexception [:message]
@impl true
def exception(value) do
msg = "did not get what was expected, got: #{inspect(value)}"
%MyAppError{message: msg}
end
end
Example
defmodule Integer.Guards do
defguard is_even(value) when is_integer(value) and rem(value, 2)
== 0
end
defmodule Collatz do
@moduledoc "Tools for working with the Collatz sequence."
import Integer.Guards
Examples
defmodule MyLogic do
defmacro unless(expr, opts) do
quote do
if !unquote(expr), unquote(opts)
end
end
end
require MyLogic
MyLogic.unless false do
IO.puts("It works")
end
Private macros are only accessible from the same module in which they
are defined.
Private macros must be defined before its usage.
Check defmacro/2 for more information, and check def/2 for rules on
naming and default arguments.
This macro defines a module with the given alias as its name and with
the given contents. It returns a tuple with four elements:
:module
the module name
the binary contents of the module
the result of evaluating the contents block
Examples
defmodule Number do
def one, do: 1
def two, do: 2
end
#=> {:module, Number, <<70, 79, 82, ...>>, {:two, 0}}
Number.one()
#=> 1
Number.two()
#=> 2
Nesting
Nesting a module inside another module affects the name of the nested
module:
defmodule Foo do
defmodule Bar do
end
end
In the example above, two modules - Foo and Foo.Bar - are created.
When nesting, Elixir automatically creates an alias to the inner module,
allowing the second module Foo.Bar to be accessed as Bar in the same
lexical scope where it's defined (the Foo module). This only happens if
the nested module is defined via an alias.
defmodule Foo.Bar do
# code
end
defmodule Foo do
alias Foo.Bar
# code here can refer to "Foo.Bar" as just "Bar"
end
Dynamic names
defmodule String.to_atom("Foo#{1}") do
# contents ...
end
Elixir will accept any module name as long as the expression passed as the
first argument to defmodule/2 evaluates to an atom. Note that, when a
dynamic name is used, Elixir won't nest the name under the current
module nor automatically set up an alias.
If you attempt to define a module that already exists, you will get a
warning saying that a module has been redefined.
There are some modules that Elixir does not currently implement but it
may be implement in the future. Those modules are reserved and defining
them will result in a compilation error:
defmodule Any do
# code
end
** (CompileError) iex:1: module Any is reserved and cannot be
defined
defoverridable(keywords_or_behaviour) (macro)
Example
defmodule DefaultMod do
defmacro __using__(_opts) do
quote do
def test(x, y) do
x + y
end
defoverridable test: 2
end
end
end
defmodule InheritMod do
use DefaultMod
def test(x, y) do
x * y + super(x, y)
end
end
As seen as in the example above, super can be used to call the default
implementation.
Example
defmodule Behaviour do
@callback foo :: any
end
defmodule DefaultMod do
defmacro __using__(_opts) do
quote do
@behaviour Behaviour
def foo do
"Override me"
end
defoverridable Behaviour
end
end
end
defmodule InheritMod do
use DefaultMod
def foo do
"Overridden"
end
end
Private functions are only accessible from within the module in which
they are defined. Trying to access a private function from outside the
module it's defined in results in an UndefinedFunctionError exception.
Examples
defmodule Foo do
def bar do
sum(1, 2)
end
Foo.bar()
#=> 3
Foo.sum(1, 2)
** (UndefinedFunctionError) undefined function Foo.sum/2
Defines a protocol.
defstruct(fields) (macro)
Defines a struct.
Examples
defmodule User do
defstruct name: nil, age: nil
end
defmodule User do
defstruct name: nil, age: 10 + 11
end
The fields argument is usually a keyword list with field names as atom
keys and default values as corresponding values. defstruct/1 also
supports a list of atoms as its argument: in that case, the atoms in the list
will be used as the struct's field names and they will all default to nil .
defmodule Post do
defstruct [:title, :content, :author]
end
Deriving
Although structs are maps, by default structs do not implement any of the
protocols implemented for maps. For example, attempting to use a
protocol with the User struct leads to an error:
MyProtocol.call(john) # it works!
For each protocol in the @derive list, Elixir will assert the protocol has
been implemented for Any . If the Any implementation defines a
__deriving__/3 callback, the callback will be invoked and it should define
the implementation module. Otherwise an implementation that simply
points to the Any implementation is automatically derived. For more
information on the __deriving__/3 callback, see Protocol.derive/3 .
Enforcing keys
Elixir also allows developers to enforce certain keys must always be given
when building the struct:
defmodule User do
@enforce_keys [:name]
defstruct name: nil, age: 10 + 11
end
Now trying to build a struct without the name key will fail:
%User{age: 21}
** (ArgumentError) the following keys must also be given when
building struct User: [:name]
defmodule User do
defstruct name: "John", age: 25
@type t :: %__MODULE__{name: String.t(), age: non_neg_integer}
end
The types of the struct fields that are not included in %User{} default to
term() (see term/0 ).
Destructures two lists, assigning each term in the right one to the
matching term in the left one.
Unlike pattern matching via = , if the sizes of the left and right lists don't
match, destructuring simply stops instead of raising an error.
Examples
In the example above, even though the right list has more entries than the
left one, destructuring works fine. If the right list is smaller, the
remaining elements are simply set to nil :
iex> destructure([x, y, z], [1])
iex> {x, y, z}
{1, nil, nil}
The left-hand side supports any expression you would use on the left-
hand side of a match:
x = 1
destructure([^x, y, z], [1, 2, 3])
The example above will only work if x matches the first value in the right
list. Otherwise, it will raise a MatchError (like the = operator would do).
exit(reason)
Stops the execution of the calling process with the given reason.
Examples
When a process reaches its end, by default it exits with reason :normal .
You can also call exit/1 explicitly if you want to terminate a process but
not signal any failure:
exit(:normal)
In case something goes wrong, you can also use exit/1 with a different
reason:
exit(:seems_bad)
If the exit reason is not :normal , all the processes linked to the process
that exited will crash (unless they are trapping exits).
OTP exits
exit(:normal)
exit(:shutdown)
exit({:shutdown, term})
CLI exits
Building on top of the exit signals mentioned above, if the process started
by the command line exits with any of the three reasons above, its exit is
considered normal and the Operating System process will exit with status
0.
exit({:shutdown, integer})
This will cause the operating system process to exit with the status given
by integer while signaling all linked Erlang processes to politely shut
down.
Any other exit reason will cause the operating system process to exit with
status 1 and linked Erlang processes to crash.
Note that this function does not load the module in case it is not loaded.
Check Code.ensure_loaded/1 for more information.
Examples
Gets a value and updates a nested data structure via the given path .
Is equivalent to:
This also works with nested structs and the struct.path.to.value way to
specify paths:
Note that in order for this macro to work, the complete path must always
be visible by this macro. See the "Paths" section below.
Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_and_update_in(users["john"].age, &{&1, &1 + 1})
{27, %{"john" => %{age: 28}, "meg" => %{age: 23}}}
Paths
A path may start with a variable, local or remote call, and must be
followed by one or more:
foo[bar] - accesses the key bar in foo ; in case foo is nil, nil is
returned
users["john"][:age]
users["john"].age
User.all()["john"].age
all_users()["john"].age
@spec get_and_update_in(
structure,
keys,
(term() | nil -> {current_value, new_value} | :pop)
) :: {current_value, new_structure :: structure}
when structure: Access.t(),
keys: [any(), ...],
current_value: Access.value(),
new_value: Access.value()
data is a nested structure (that is, a map, keyword list, or struct that
implements the Access behaviour).
The fun argument receives the value of key (or nil if key is not present)
and must return one of the following values:
:pop , which implies that the current value under key should be
removed from the structure and returned.
This function uses the Access module to traverse the structures according
to the given keys , unless the key is a function, which is detailed in a later
section.
Examples
This function is useful when there is a need to retrieve the current value
(or something calculated in function of the current value) and update it at
the same time. For example, it could be used to read the current age of a
user while increasing it by one in one pass:
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_and_update_in(users, ["john", :age], &{&1, &1 + 1})
{27, %{"john" => %{age: 28}, "meg" => %{age: 23}}}
Functions as keys
When one of the keys is a function, the function is invoked. In the example
below, we use a function to get and increment all ages inside a list:
iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}]
iex> all = fn :get_and_update, data, next ->
...> data |> Enum.map(next) |> Enum.unzip()
...> end
iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1})
{[27, 23], [%{name: "john", age: 28}, %{name: "meg", age: 24}]}
If the previous value before invoking the function is nil , the function will
receive nil as a value and must handle it accordingly (be it by failing or
providing a sane default).
The Access module ships with many convenience accessor functions, like
the all anonymous function defined above. See Access.all/0 ,
Access.key/2 , and others as examples.
get_in(data, keys)
Uses the Access module to traverse the structures according to the given
keys , unless the key is a function, which is detailed in a later section.
Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_in(users, ["john", :age])
27
Note that get_in exists mostly for convenience and parity with
functionality found in put_in and update_in . Given Elixir provides
pattern matching, it can often be more expressive for deep data traversal,
for example:
case users do
%{"unknown" => %{age: age}} -> age
_ -> default_value
end
Functions as keys
iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}]
iex> all = fn :get, data, next -> Enum.map(data, next) end
iex> get_in(users, [all, :age])
[27, 23]
If the previous value before invoking the function is nil , the function will
receive nil as a value and must handle it accordingly.
The Access module ships with many convenience accessor functions, like
the all anonymous function defined above. See Access.all/0 ,
Access.key/2 , and others as examples.
The good news is that structs have predefined shape. Therefore, you can
write instead:
some_struct.some_key.nested_key
If, by any chance, some_key can return nil, you can always fallback to
pattern matching to provide nested struct handling:
case some_struct do
%{some_key: %{nested_key: value}} -> value
%{} -> nil
end
This macro expects the first argument to be a condition and the second
argument to be a keyword list.
One-liner examples
Blocks examples
It's also possible to pass a block to the if/2 macro. The first example
above would be translated to:
if foo do
bar
end
Note that do/end become delimiters. The second example would translate
to:
if foo do
bar
else
baz
end
In order to compare more than two clauses, the cond/1 macro has to be
used.
Options
Examples
iex> inspect(:foo)
":foo"
iex> inspect('bar')
"'bar'"
Note that the Inspect protocol does not necessarily return a valid
representation of an Elixir term. In such cases, the inspected result must
start with # . For example, inspecting a function will return:
The Inspect protocol can be derived to hide certain fields from structs, so
they don't show up in logs, inspects and similar. See the "Deriving"
section of the documentation of the Inspect protocol for more
information.
macro_exported?(module, macro, arity)
Returns true if module is loaded and contains a public macro with the
given arity , otherwise false .
Note that this function does not load the module in case it is not loaded.
Check Code.ensure_loaded/1 for more information.
Examples
make_ref()
Examples
make_ref()
#=> #Reference<0.0.0.135>
Examples
iex> match?(1, 1)
true
iex> a = 1
iex> match?(^a, 1)
true
iex> match?(_x, 1)
true
iex> binding()
[]
max(first, second)
@spec max(first, second) :: first | second when first: term(), second: term()
Returns the biggest of the two given terms according to their structural
comparison.
Examples
iex> max(1, 2)
2
iex> max(:a, :b)
:b
min(first, second)
@spec min(first, second) :: first | second when first: term(), second: term()
Returns the smallest of the two given terms according to their structural
comparison.
Examples
iex> min(1, 2)
1
iex> min("foo", "bar")
"bar"
pop_in(path) (macro)
Pops a key from the nested structure via the given path .
This is similar to pop_in/2 , except the path is extracted via a macro rather
than passing a list. For example:
pop_in(opts[:foo][:bar])
Is equivalent to:
Note that in order for this macro to work, the complete path must always
be visible by this macro. For more information about the supported path
expressions, please check get_and_update_in/2 docs.
Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> pop_in(users["john"][:age])
{27, %{"john" => %{}, "meg" => %{age: 23}}}
In case any entry returns nil , its key will be removed and the deletion
will be considered a success.
pop_in(data, keys)
@spec pop_in(data, [Access.get_and_update_fun(term(), data) | term(), ...]) ::
{term(), data}
when data: Access.container()
Uses the Access protocol to traverse the structures according to the given
keys , unless the key is a function. If the key is a function, it will be
invoked as specified in get_and_update_in/3 .
Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> pop_in(users, ["john", :age])
{27, %{"john" => %{}, "meg" => %{age: 23}}}
In case any entry returns nil , its key will be removed and the deletion
will be considered a success.
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> pop_in(users, ["jane", :age])
{nil, %{"john" => %{age: 27}, "meg" => %{age: 23}}}
Examples
This is similar to put_in/3 , except the path is extracted via a macro rather
than passing a list. For example:
put_in(opts[:foo][:bar], :baz)
Is equivalent to:
This also works with nested structs and the struct.path.to.value way to
specify paths:
put_in(struct.foo.bar, :baz)
Note that in order for this macro to work, the complete path must always
be visible by this macro. For more information about the supported path
expressions, please check get_and_update_in/2 docs.
Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users["john"][:age], 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users["john"].age, 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
Uses the Access module to traverse the structures according to the given
keys , unless the key is a function. If the key is a function, it will be
invoked as specified in get_and_update_in/3 .
Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users, ["john", :age], 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
In case any of the entries in the middle returns nil , an error will be raised
when trying to access it next.
raise(message) (macro)
Raises an exception.
If message is an atom, it just calls raise/2 with the atom as the first
argument and [] as the second one.
Examples
try do
1 + :foo
rescue
x in [ArithmeticError] ->
IO.puts("that was expected")
raise x
end
Raises an exception.
Calls the exception/1 function on the given argument (which has to be a
module name like ArgumentError or RuntimeError ) passing attributes in
order to retrieve the exception struct.
Examples
Examples
try do
raise "oops"
rescue
exception ->
reraise exception, __STACKTRACE__
end
Examples
try do
raise "oops"
rescue
exception ->
reraise WrapperError, [exception: exception], __STACKTRACE__
end
send(dest, message)
dest may be a remote or local PID, a local port, a locally registered name,
or a tuple in the form of {registered_name, node} for a registered name at
another node.
Examples
Examples
iex> ~C(foo)
'foo'
iex> ~C(f#{o}o)
'f\#{o}o'
sigil_c(term, modifiers) (macro)
Examples
iex> ~c(foo)
'foo'
iex> ~c(f#{:o}o)
'foo'
iex> ~c(f\#{:o}o)
'f\#{:o}o'
By default, this sigil uses the built-in Calendar.ISO , which requires dates
to be written in the ISO8601 format:
~D[yyyy-mm-dd]
such as:
~D[2015-01-13]
~D[SOME-REPRESENTATION My.Alternative.Calendar]
The lower case ~d variant does not exist as interpolation and escape
characters are not useful for date sigils.
Examples
iex> ~D[2015-01-13]
~D[2015-01-13]
By default, this sigil uses the built-in Calendar.ISO , which requires naive
date times to be written in the ISO8601 format:
~N[yyyy-mm-dd hh:mm:ss]
~N[yyyy-mm-dd hh:mm:ss.ssssss]
~N[yyyy-mm-ddThh:mm:ss.ssssss]
such as:
~N[2015-01-13 13:00:07]
~N[2015-01-13T13:00:07.123]
~N[SOME-REPRESENTATION My.Alternative.Calendar]
The lower case ~n variant does not exist as interpolation and escape
characters are not useful for date time sigils.
Examples
iex> ~N[2015-01-13 13:00:07]
~N[2015-01-13 13:00:07]
iex> ~N[2015-01-13T13:00:07.001]
~N[2015-01-13 13:00:07.001]
Examples
Examples
Examples
iex> ~S(foo)
"foo"
iex> ~S(f#{o}o)
"f\#{o}o"
iex> ~S(\o/)
"\\o/"
However, if you want to re-use the sigil character itself on the string, you
need to escape it:
iex> ~S((\))
"()"
Examples
iex> ~s(foo)
"foo"
iex> ~s(f#{:o}o)
"foo"
iex> ~s(f\#{:o}o)
"f\#{:o}o"
By default, this sigil uses the built-in Calendar.ISO , which requires times
to be written in the ISO8601 format:
~T[hh:mm:ss]
~T[hh:mm:ss.ssssss]
such as:
~T[13:00:07]
~T[13:00:07.123]
~T[SOME-REPRESENTATION My.Alternative.Calendar]
The lower case ~t variant does not exist as interpolation and escape
characters are not useful for time sigils.
Examples
iex> ~T[13:00:07]
~T[13:00:07]
iex> ~T[13:00:07.001]
~T[13:00:07.001]
By default, this sigil uses the built-in Calendar.ISO , which requires UTC
date times to be written in the ISO8601 format:
~U[yyyy-mm-dd hh:mm:ssZ]
~U[yyyy-mm-dd hh:mm:ss.ssssssZ]
~U[yyyy-mm-ddThh:mm:ss.ssssss+00:00]
such as:
~U[2015-01-13 13:00:07Z]
~U[2015-01-13T13:00:07.123+00:00]
~U[SOME-REPRESENTATION My.Alternative.Calendar]
The lower case ~u variant does not exist as interpolation and escape
characters are not useful for date time sigils.
Examples
iex> ~U[2015-01-13 13:00:07Z]
~U[2015-01-13 13:00:07Z]
iex> ~U[2015-01-13T13:00:07.001+00:00]
~U[2015-01-13 13:00:07.001Z]
Modifiers
Examples
Modifiers
Examples
iex> ~w(foo #{:bar} baz)
["foo", "bar", "baz"]
spawn(fun)
Typically developers do not use the spawn functions, instead they use
abstractions such as Task , GenServer and Agent , built on top of spawn ,
that spawns processes with more conveniences in terms of introspection
and debugging.
The anonymous function receives 0 arguments, and may return any value.
Examples
current = self()
child = spawn(fn -> send(current, {self(), 1 + 2}) end)
receive do
{^child, 3} -> IO.puts("Received 3 back")
end
Spawns the given function fun from the given module passing it the given
args and returns its PID.
Typically developers do not use the spawn functions, instead they use
abstractions such as Task , GenServer and Agent , built on top of spawn ,
that spawns processes with more conveniences in terms of introspection
and debugging.
Examples
spawn_link(fun)
Spawns the given function, links it to the current process, and returns its
PID.
Typically developers do not use the spawn functions, instead they use
abstractions such as Task , GenServer and Agent , built on top of spawn ,
that spawns processes with more conveniences in terms of introspection
and debugging.
Check the Process module for more process-related functions. For more
information on linking, check Process.link/1 .
The anonymous function receives 0 arguments, and may return any value.
Examples
current = self()
child = spawn_link(fn -> send(current, {self(), 1 + 2}) end)
receive do
{^child, 3} -> IO.puts("Received 3 back")
end
Spawns the given function fun from the given module passing it the given
args , links it to the current process, and returns its PID.
Typically developers do not use the spawn functions, instead they use
abstractions such as Task , GenServer and Agent , built on top of spawn ,
that spawns processes with more conveniences in terms of introspection
and debugging.
Check the Process module for more process-related functions. For more
information on linking, check Process.link/1 .
Examples
spawn_monitor(fun)
Spawns the given function, monitors it and returns its PID and
monitoring reference.
Typically developers do not use the spawn functions, instead they use
abstractions such as Task , GenServer and Agent , built on top of spawn ,
that spawns processes with more conveniences in terms of introspection
and debugging.
Check the Process module for more process-related functions.
The anonymous function receives 0 arguments, and may return any value.
Examples
current = self()
spawn_monitor(fn -> send(current, {self(), 1 + 2}) end)
Spawns the given module and function passing the given args, monitors it
and returns its PID and monitoring reference.
Typically developers do not use the spawn functions, instead they use
abstractions such as Task , GenServer and Agent , built on top of spawn ,
that spawns processes with more conveniences in terms of introspection
and debugging.
Examples
Examples
defmodule User do
defstruct name: "john"
end
struct(User)
#=> %User{name: "john"}
Pipes value to the given fun and returns the value itself.
Examples
Most commonly, this is used in pipelines. For example, let's suppose you
want to inspect part of a data structure. You could write:
%{a: 1}
|> Map.update!(:a, & &1 + 2)
|> tap(&IO.inspect(&1.a))
|> Map.update!(:a, & &1 * 2)
throw(term)
to_charlist(term) (macro)
Examples
iex> to_charlist(:foo)
'foo'
to_string(term) (macro)
Examples
iex> to_string(:foo)
"foo"
unless(condition, clauses) (macro)
This macro evaluates and returns the do block passed in as the second
argument if condition evaluates to a falsy value ( false or nil ).
Otherwise, it returns the value of the else block if present or nil if not.
Examples
Is equivalent to:
Note that in order for this macro to work, the complete path must always
be visible by this macro. For more information about the supported path
expressions, please check get_and_update_in/2 docs.
Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> update_in(users["john"][:age], &(&1 + 1))
%{"john" => %{age: 28}, "meg" => %{age: 23}}
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> update_in(users["john"].age, &(&1 + 1))
%{"john" => %{age: 28}, "meg" => %{age: 23}}
Uses the Access module to traverse the structures according to the given
keys , unless the key is a function. If the key is a function, it will be
invoked as specified in get_and_update_in/3 .
data is a nested structure (that is, a map, keyword list, or struct that
implements the Access behaviour). The fun argument receives the value
of key (or nil if key is not present) and the result replaces the value in
the structure.
Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> update_in(users, ["john", :age], &(&1 + 1))
%{"john" => %{age: 28}, "meg" => %{age: 23}}
In case any of the entries in the middle returns nil , an error will be raised
when trying to access it next.
When calling:
the __using__/1 macro from the MyModule module is invoked with the
second argument passed to use as its argument. Since __using__/1 is a
macro, all the usual macro rules apply, and its return value should be
quoted code that is then inserted where use/2 is called.
Examples
For example, to write test cases using the ExUnit framework provided
with Elixir, a developer should use the ExUnit.Case module:
defmodule AssertionTest do
use ExUnit.Case, async: true
In this example, Elixir will call the __using__/1 macro in the ExUnit.Case
module with the keyword list [async: true] as its argument.
defmodule ExUnit.Case do
defmacro __using__(opts) do
# do something with opts
quote do
# return some code to inject in the caller
end
end
end
Best practices
__using__/1 is typically used when there is a need to set some state (via
module attributes) or callbacks (like @before_compile , see the
documentation for Module for more information) into the caller.
defmodule MyModule do
defmacro __using__(_opts) do
quote do
import MyModule.Foo
import MyModule.Bar
import MyModule.Baz
alias MyModule.Repo
end
end
end
However, do not provide __using__/1 if all it does is to import, alias or
require the module itself. For example, avoid this:
defmodule MyModule do
defmacro __using__(_opts) do
quote do
import MyModule
end
end
end
Examples
iex> Kernel.var!(example) = 1
1
iex> Kernel.var!(example)
1
Pipe operator.
This operator introduces the expression on the left-hand side as the first
argument to the function call on the right-hand side.
Examples
The |> operator is mostly useful when there is a desire to execute a series
of operations resembling a pipeline:
In the example above, the list [1, [2], 3] is passed as the first argument
to the List.flatten/1 function, then the flattened list is passed as the
first argument to the Enum.map/2 function which doubles each element of
the list.
Pitfalls
There are two common pitfalls when using the pipe operator.
The first one is related to operator precedence. For example, the following
expression:
Translates to:
then/2 is most commonly used when you want to pipe to a function but
the value is expected outside of the first argument, such as above. By
replacing some_fun by its value, we get:
Examples
iex> Enum.empty?([1]) || 1
1
Note that, unlike or/2 , this operator accepts any expression as the first
argument, not only booleans.