Elixir also has special forms that are always imported and
cannot be skipped. These are described in Kernel.SpecialForms.

The standard library

Kernel provides the basic capabilities the Elixir standard library
is built on top of. It is recommended to explore the standard library
for advanced functionality. Here are the main groups of modules in the
standard library (this list is not a complete reference, see the
documentation sidebar for all entries).

Protocols

Protocols add polymorphic dispatch to Elixir. They are contracts
implementable by data types. See defprotocol/2 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:

defdrive(%User{age:age})whenage>=16do...end

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.

Inlining

Some of the functions described in this module are inlined by
the Elixir compiler into their Erlang counterparts in the
module:erlang.
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

Those functions will be explicitly marked in their docs as
"inlined by the compiler".

Truthy and falsy values

Besides the booleans true and false, Elixir has the
concept of a "truthy" or "falsy" value.

a value is truthy when it is neither false nor nil

a value is falsy when it is either false or nil

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.

Provides a short-circuit operator that evaluates and returns the second
expression only if the first one does not evaluate to a truthy value (that is,
it is either nil or false). Returns the first expression otherwise.

Examples

left === right

Specs

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

left in right

Checks if the element on the left-hand side is a member of the
collection on the right-hand side.

Examples

iex> x=1iex> xin[1,2,3]true

This operator (which is a macro) simply translates to a call to
Enum.member?/2. The example above would translate to:

Enum.member?([1,2,3],x)

Elixir also supports left not in right, which evaluates to
not(left in right):

iex> x=1iex> xnotin[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:

whenxin[1,2,3]

translates to:

whenx===1orx===2orx===3

When using ranges:

whenxin1..3

translates to:

whenis_integer(x)andx>=1andx<=3

Note that only integers can be considered inside a range by in.

AST considerations

left not in right is parsed by the compiler into the AST:

{:not,_,[{:in,_,[left,right]}]}

This is the same AST as not(left in right).

Additionally, Macro.to_string/2 will translate all occurrences of
this AST to left not in right.

left ++ right

Specs

The complexity of a ++ b is proportional to length(a), so avoid repeatedly
appending to lists of arbitrary length, for example, list ++ [element].
Instead, consider prepending via [element | rest] and then reversing.

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.

left -- right

Specs

Removes the first occurrence of an element on the left list
for each element on the right.

The complexity of a -- b is proportional to length(a) * length(b),
meaning that it will be very slow if both a and b are long lists.
In such cases, consider converting each list to a MapSet and using
MapSet.difference/2.

Inlined by the compiler.

Examples

first..last

If last is larger than first, the range will be increasing from
first to last. If first is larger than last, the range will be
decreasing from first to last. If first is equal to last, the range
will contain one element, which is the number itself.

@expr

The canonical example for attributes is annotating that a module
implements an OTP behaviour, such as GenServer:

defmoduleMyServerdo@behaviourGenServer# ... callbacks ...end

By default Elixir supports all the module attributes supported by Erlang, but
custom attributes can be used as well:

defmoduleMyServerdo@my_data13IO.inspect(@my_data)#=> 13end

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.

It is important to note that reading an attribute takes a snapshot of
its current value. In other words, the value is read at compilation
time and not at runtime. Check the Module module for other functions
to manipulate module attributes.

left |> right

This operator introduces the expression on the left-hand side as
the first argument to the function call on the right-hand side.

Examples

iex> [1,[2],3]|>List.flatten()[1,2,3]

The example above is the same as calling List.flatten([1, [2], 3]).

The |> operator is mostly useful when there is a desire to execute a series
of operations resembling a pipeline:

iex> [1,[2],3]|>List.flatten()|>Enum.map(fnx->x*2end)[2,4,6]

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.

In other words, the expression above simply translates to:

Enum.map(List.flatten([1,[2],3]),fnx->x*2end)

Pitfalls

There are two common pitfalls when using the pipe operator.

The first one is related to operator precedence. For example,
the following expression:

String.graphemes"Hello"|>Enum.reverse

Translates to:

String.graphemes("Hello"|>Enum.reverse())

which results in an error as the Enumerable protocol is not defined
for binaries. Adding explicit parentheses resolves the ambiguity:

String.graphemes("Hello")|>Enum.reverse()

Or, even better:

"Hello"|>String.graphemes()|>Enum.reverse()

The second pitfall is that the |> operator works on calls.
For example, when you write:

"Hello"|>some_function()

Elixir sees the right-hand side is a function call and pipes
to it. This means that, if you want to pipe to an anonymous
or captured function, it must also be explicitly called.

Given the anonymous function:

fun=fnx->IO.puts(x)endfun.("Hello")

This won't work as it will rather try to invoke the local
function fun:

"Hello"|>fun()

This works:

"Hello"|>fun.()

As you can see, the |> operator retains the same semantics
as when the pipe is not used since both require the fun.(...)
notation.

left || right

Provides a short-circuit operator that evaluates and returns the second
expression only if the first one does not evaluate to a truthy value (that is,
it is either nil or false). Returns the first expression otherwise.

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.

When defining a function with default arguments as well as multiple
explicitly declared clauses, you must write a function head that declares the
defaults. For example:

Note that \\ can't be used with anonymous functions because they
can only have a sole arity.

Function and variable names

Function and variable names have the following syntax:
A lowercase ASCII letter or an underscore, followed by any number of
lowercase or uppercase ASCII letters, numbers, or underscores.
Optionally they can end in either an exclamation mark or a question mark.

For variables, any identifier starting with an underscore should indicate an
unused variable. For example:

deffoo(bar)do[]end#=> warning: variable bar is unuseddeffoo(_bar)do[]end#=> no warningdeffoo(_bar)do_barend#=> warning: the underscored variable "_bar" is used after being set

rescue/catch/after/else

Function bodies support rescue, catch, after, and else as Kernel.SpecialForms.try/1
does (known as "implicit try"). For example, the following two functions are equivalent:

defdelegate(funs, opts)

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.

Delegation only works with functions; delegating macros is not supported.

defexception(fields)

Exceptions are structs backed by a module that implements
the Exception behaviour. The Exception behaviour requires
two functions to be implemented:

exception/1 - receives the arguments given to raise/2
and returns the exception struct. The default implementation
accepts either a set of keyword arguments that is merged into
the struct or a string to be used as the exception's message.

message/1 - receives the exception struct and must return its
message. Most commonly exceptions have a message field which
by default is accessed by this function. However, if an exception
does not have a message field, this function must be explicitly
implemented.

defguard(guard)

Specs

It raises at compile time if the definition uses expressions that aren't
allowed in guards, and otherwise creates a macro that can be used both inside
or outside guards.

Note the convention in Elixir is to name functions/macros allowed in
guards with the is_ prefix, such as is_list/1. If, however, the
function/macro returns a boolean and is not allowed in guards, it should
have no prefix and end with a question mark, such as Keyword.keyword?/1.

Example

defmoduleInteger.Guardsdodefguardis_even(value)whenis_integer(value)andrem(value,2)==0enddefmoduleCollatzdo@moduledoc"Tools for working with the Collatz sequence."importInteger.Guards@doc"Determines the number of steps `n` takes to reach `1`."# If this function never converges, please let me know what `n` you used.defconverge(n)whenn>0,do:step(n,0)defpstep(1,step_count)dostep_countenddefpstep(n,step_count)whenis_even(n)dostep(div(n,2),step_count+1)enddefpstep(n,step_count)dostep(3*n+1,step_count+1)endend

Examples

Nesting

Nesting a module inside another module affects the name of the nested module:

defmoduleFoododefmoduleBardoendend

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.

If the Foo.Bar module is moved somewhere else, the references to Bar in
the Foo module need to be updated to the fully-qualified name (Foo.Bar) or
an alias has to be explicitly set in the Foo module with the help of
Kernel.SpecialForms.alias/2.

defmoduleFoo.Bardo# codeenddefmoduleFoodoaliasFoo.Bar# code here can refer to "Foo.Bar" as just "Bar"end

Dynamic names

Elixir module names can be dynamically generated. This is very
useful when working with macros. For instance, one could write:

defmoduleString.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.

Reserved module names

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:

defmoduleAnydo# codeend** (CompileError) iex:1: module Any is reserved and cannot be defined

Example

As seen as in the example above, super can be used to call the default
implementation.

If @behaviour has been defined, defoverridable can also be called with a
module as an argument. All implemented callbacks from the behaviour above the
call to defoverridable will be marked as overridable.

defp(call, expr \\ nil)

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

Struct fields are evaluated at compile-time, which allows
them to be dynamic. In the example below, 10 + 11 is
evaluated at compile-time and the age field is stored
with value 21:

defmoduleUserdodefstructname:nil,age:10+11end

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.

defmodulePostdodefstruct[: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:

defstruct/1, however, allows protocol implementations to be
derived. This can be done by defining a @derive attribute as a
list before invoking defstruct/1:

defmoduleUserdo@derive[MyProtocol]defstructname:nil,age:10+11endMyProtocol.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

When building a struct, Elixir will automatically guarantee all keys
belongs to the struct:

It is recommended to only use the struct syntax when defining the struct's
type. When referring to another struct it's better to use User.t instead of
%User{}.

The types of the struct fields that are not included in %User{} default to
term() (see term/0).

Structs whose internal structure is private to the local module (pattern
matching them or directly accessing their fields should not be allowed) should
use the @opaque attribute. Structs whose internal structure is public should
use @type.

exit(reason)

Specs

Since evaluating this function causes the process to terminate,
it has no return value.

Inlined by the compiler.

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

Exits are used by the OTP to determine if a process exited abnormally
or not. The following exits are considered "normal":

exit(:normal)

exit(:shutdown)

exit({:shutdown, term})

Exiting with any other reason is considered abnormal and treated
as a crash. This means the default supervisor behaviour kicks in,
error reports are emitted, and so forth.

This behaviour is relied on in many different places. For example,
ExUnit uses exit(:shutdown) when exiting the test process to
signal linked processes, supervision trees and so on to politely
shut down too.

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.

It is, however, possible to customize the operating system exit
signal by invoking:

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.

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:

a two-element tuple {get_value, new_value}. In this case,
get_value is the retrieved value which can possibly be operated on before
being returned. new_value is the new value to be stored under key.

: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:

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:

inspect(fna,b->a+bend)#=> #Function<...>

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.

max(first, second)

Specs

Returns the biggest of the two given terms according to
Erlang's term ordering.

If the terms compare equal, the first one is returned.

Inlined by the compiler.

Examples

iex> max(1,2)2iex> max(:a,:b):b

Using Erlang's term ordering means that comparisons are
structural and not semantic. For example, when comparing dates:

iex> max(~D[2017-03-31],~D[2017-04-01])~D[2017-03-31]

In the example above, max/2 returned March 31st instead of April 1st
because the structural comparison compares the day before the year. In
such cases it is common for modules to provide functions such as
Date.compare/2 that perform semantic comparison.

min(first, second)

Specs

Returns the smallest of the two given terms according to
Erlang's term ordering.

If the terms compare equal, the first one is returned.

Inlined by the compiler.

Examples

iex> min(1,2)1iex> min("foo","bar")"bar"

Using Erlang's term ordering means that comparisons are
structural and not semantic. For example, when comparing dates:

iex> min(~D[2017-03-31],~D[2017-04-01])~D[2017-04-01]

In the example above, min/2 returned April 1st instead of March 31st
because the structural comparison compares the day before the year. In
such cases it is common for modules to provide functions such as
Date.compare/2 that perform semantic comparison.

sigil_R(term, modifiers)

It returns a regular expression pattern without interpolations and
without escape characters. Note it still supports escape of Regex
tokens (such as escaping + or ?) and it also requires you to
escape the closing sigil character itself if it appears on the Regex.

spawn(fun)

Specs

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.

spawn(module, fun, args)

Specs

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)

Specs

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.

spawn_link(module, fun, args)

Specs

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)

Specs

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.

Examples

spawn_monitor(module, fun, args)

Specs

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

struct(struct, fields \\ [])

Specs

The struct argument may be an atom (which defines defstruct)
or a struct itself. The second argument is any Enumerable that
emits two-element tuples (key-value pairs) during enumeration.

Keys in the Enumerable that don't exist in the struct are automatically
discarded. Note that keys must be atoms, as only atoms are allowed when
defining a struct. If keys in the Enumerable are duplicated, the last
entry will be taken (same behaviour as Map.new/1).

This function is useful for dynamically creating and updating structs, as
well as for converting maps to structs; in the latter case, just inserting
the appropriate :__struct__ field into the map may not be enough and
struct/2 should be used instead.

struct!(struct, fields \\ [])

Specs

The function struct!/2 emulates the compile time behaviour
of structs. This means that:

when building a struct, as in struct!(SomeStruct, key: :value),
it is equivalent to %SomeStruct{key: :value} and therefore this
function will check if every given key-value belongs to the struct.
If the struct is enforcing any key via @enforce_keys, those will
be enforced as well;

when updating a struct, as in struct!(%SomeStruct{}, key: :value),
it is equivalent to %SomeStruct{struct | key: :value} and therefore this
function will check if every given key-value belongs to the struct.
However, updating structs does not enforce keys, as keys are enforced
only when building;

Examples

unless(condition, clauses)

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.

update_in(data, keys, fun)

Specs

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.

use(module, opts \\ [])

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, in order to write test cases using the ExUnit framework
provided with Elixir, a developer should use the ExUnit.Case module:

In such cases, developers should instead import or alias the module
directly, so that they can customize those as they wish,
without the indirection behind use/2.

Finally, developers should also avoid defining functions inside
the __using__/1 callback, unless those functions are the default
implementation of a previously defined @callback or are functions
meant to be overridden (see defoverridable/1). Even in these cases,
defining functions should be seen as a "last resort".

In case you want to provide some existing functionality to the user module,
please define it in a module which will be imported accordingly; for example,
ExUnit.Case doesn't define the test/3 macro in the module that calls
use ExUnit.Case, but it defines ExUnit.Case.test/3 and just imports that
into the caller when used.