Kernel

Kernel provides the default macros and functions Elixir imports into your environment. These macros and functions can be skipped or cherry-picked via the import macro. For instance, if you want to tell Elixir not to import the if macro, you can do:

import Kernel, except: [if: 2]

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

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 (builtin 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".

Source

Summary

!arg

Receives any argument and returns true if it is false or nil. Returns false otherwise. Not allowed in guard clauses

left != right

Returns true if the two items are not equal

left !== right

Returns true if the two items do not match

left && right

Provides a short-circuit operator that evaluates and returns the second expression only if the first one evaluates to true (i.e. it is not nil nor false). Returns the first expression otherwise

left * right

Arithmetic multiplication

left ++ right

Concatenates two lists

+value

Arithmetic unary plus

left + right

Arithmetic plus

left -- right

Removes the first occurrence of an item on the left for each item on the right

-value

Arithmetic unary minus

left - right

Arithmetic minus

first .. last

Returns a range with the specified start and end. Includes both ends

left / right

Arithmetic division

left < right

Returns true if left is less than right

left <= right

Returns true if left is less than or equal to right

left <> right

Concatenates two binaries

left == right

Returns true if the two items are equal

left === right

Returns true if the two items are match

left =~ right

Matches the term on the left against the regular expression or string on the right. Returns true if left matches right (if it's a regular expression) or contains right (if it's a string)

left > right

Returns true if left is more than right

left >= right

Returns true if left is more than or equal to right

@expr

This macro is a shortcut to read and add attributes to the module being compiled. Elixir module attributes are similar to Erlang's with some differences. The canonical example for attributes is annotating that a module implements the OTP behaviour called gen_server:

abs(number)

Returns an integer or float which is the arithmetical absolute value of number

access(element, args)

Access the given element using the qualifier according to the Access protocol. All calls in the form foo[bar] are translated to access(foo, bar)

alias!(alias)

When used inside quoting, marks that the alias should not be hygienezed. This means the alias will be expanded when the macro is expanded

left and right

Boolean and. Requires only the first argument to be a boolean since it short-circuits

apply(fun, args)

Invokes the given fun with the array of arguments args

apply(module, fun, args)

Invokes the given fun from module with the array of arguments args

atom_to_binary(some_atom)

Returns a binary which corresponds to the text representation of some_atom in UTF8 encoding

atom_to_list(atom)

Returns a string which corresponds to the text representation of atom

binary_part(binary, start, length)

Extracts the part of the binary starting at start with length length. Binaries are zero-indexed

binary_to_atom(some_binary)

Returns the atom whose text representation is some_binary in UTF8 encoding

binary_to_existing_atom(some_binary)

Works like binary_to_atom/1 but the atom must exist

binary_to_float(some_binary)

Returns a float whose text representation is some_binary

binary_to_integer(some_binary)

Returns a integer whose text representation is some_binary

binary_to_integer(some_binary, base)

Returns an integer whose text representation in base base is some_binary

binding()

Returns the binding as a keyword list where the variable name is the key and the variable value is the value

binding(list)

Receives a list of atoms at compilation time and returns the binding of the given variables as a keyword list where the variable name is the key and the variable value is the value

binding(list, context)

Receives a list of atoms at compilation time and returns the binding of the given variables in the given context as a keyword list where the variable name is the key and the variable value is the value

bit_size(bitstring)

Returns an integer which is the size in bits of bitstring

bitstring_to_list(bitstring)

Returns a list of integers which correspond to the bytes of bitstring

byte_size(bitstring)

Returns an integer which is the number of bytes needed to contain bitstring. (That is, if the number of bits in bitstring is not divisible by 8, the resulting number of bytes will be rounded up.)

cond(list1)

Evaluates the expression corresponding to the first clause that evaluates to true. Raises an error if all conditions evaluate to to nil or false

def(call, expr \\ nil)

Defines a function with the given name and contents

defdelegate(funs, opts)

Defines the given functions in the current module that will delegate to the given target. Functions defined with defdelegate are public and are allowed to be invoked from external. If you find yourself wishing to define a delegation as private, you should likely use import instead

defexception(name, fields, do_block \\ [])

Defines an exception

defimpl(name, opts, do_block \\ [])

Defines an implementation for the given protocol. See defprotocol/2 for examples

defmacro(call, expr \\ nil)

Defines a macro with the given name and contents

defmacrop(call, expr \\ nil)

Defines a macro that is private. Private macros are only accessible from the same module in which they are defined

defmodule(alias, list2)

Defines a module given by name with the given contents

defoverridable(tuples)

Makes the given functions in the current module overridable. An overridable function is lazily defined, allowing a developer to customize it

defp(call, expr \\ nil)

Defines a function that is private. Private functions are only accessible from within the module in which they are defined

defprotocol(name, list2)

Defines a module as a protocol and specifies the API that should be defined by its implementations

defrecord(name, fields, do_block \\ [])

Exports a module with a record definition and runtime operations

defrecordp(name, tag \\ nil, fields)

Defines a set of private macros to manipulate a record definition

destructure(left, right)

Allows you to destructure two lists, assigning each term in the right to the matching term in the left. Unlike pattern matching via =, if the sizes of the left and right lists don't match, destructuring simply stops instead of raising an error

div(left, right)

Performs an integer division

elem(tuple, index)

Get the element at the zero-based index in tuple

exit(reason)

Stops the execution of the calling process with the given reason

float_to_binary(some_float)

Returns a binary which corresponds to the text representation of some_float

float_to_binary(float, options)

Returns a binary which corresponds to the text representation of float

float_to_list(number)

Returns a char list which corresponds to the text representation of the given float

float_to_list(float, options)

Returns a list which corresponds to the text representation of float

function_exported?(module, function, arity)

Returns true if the module is loaded and contains a public function with the given arity, otherwise false

hd(list)

Returns the head of a list, raises badarg if the list is empty

if(condition, clauses)

Provides an if macro. This macro expects the first argument to be a condition and the rest are keyword arguments

left in right

Checks if the element on the left side is member of the collection on the right side

inspect(arg, opts \\ [])

Inspect the given argument according to the Inspect protocol. The second argument is a keywords list with options to control inspection

integer_to_binary(some_integer)

Returns a binary which corresponds to the text representation of some_integer

integer_to_binary(some_integer, base)

Returns a binary which corresponds to the text representation of some_integer in base base

integer_to_list(number)

Returns a char list which corresponds to the text representation of the given integer

integer_to_list(number, base)

Returns a char list which corresponds to the text representation of the given integer in the given case

iolist_size(item)

Returns the size of an iolist

iolist_to_binary(item)

Returns a binary which is made from the integers and binaries in iolist

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(thing)

Checks if the given structure is an exception

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_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_range(thing)

Checks if the given argument is a range

is_record(thing)

Checks if the given argument is a record

is_record(thing, kind)

Checks if the given structure is a record. It is basically a convenient macro that checks the structure is a tuple and the first element matches the given kind

is_reference(term)

Returns true if term is a reference; otherwise returns false

is_regex(thing)

Checks if the given argument is a regex

is_tuple(term)

Returns true if term is a tuple; otherwise returns false

length(list)

Returns the length of list

list_to_atom(list)

Returns the atom whose text representation is list

list_to_bitstring(bitstring_list)

Returns a bitstring which is made from the integers and bitstrings in bitstring_list. (the last tail in bitstring_list is allowed to be a bitstring.)

list_to_existing_atom(list)

Returns the atom whose text representation is list, but only if there already exists such atom

list_to_float(list)

Returns the float whose text representation is list

list_to_integer(list)

Returns an integer whose text representation is list

list_to_integer(list, base)

Returns an integer whose text representation in base base is list

list_to_tuple(list)

Returns a tuple which corresponds to list. list can contain any Erlang terms

macro_exported?(module, macro, arity)

Returns true if the module is loaded and contains a public macro with the given arity, otherwise false

make_ref()

Returns an almost unique reference

match?(pattern, expr)

A convenient macro that checks if the right side matches the left side. The left side is allowed to be a match pattern

max(first, second)

Return the biggest of the two given terms according to Erlang's term ordering. If the terms compare equal, the first one is returned

min(first, second)

Return the smallest of the two given terms according to Erlang's term ordering. If the terms compare equal, the first one is returned

nil?(x)

Checks if the given argument is nil or not. Allowed in guard clauses

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 arg

Boolean not. Argument must be a boolean

left or right

Boolean or. Requires only the first argument to be a boolean since it short-circuits

raise(msg)

Raises an error

raise(exception, args)

Raises an error

raise(exception, args, stacktrace)

Re-raises an exception with the given stacktrace

rem(left, right)

Calculates the remainder of an integer division

round(number)

Returns an integer by rounding the given number

self()

Returns the pid (process identifier) of the calling process

send(dest, msg)

Sends a message to the given dest and returns the message

set_elem(tuple, index, value)

Sets the element in tuple at the zero-based index to the given value

sigil_C(arg1, list2)

Handles the sigil ~C. It simply returns a char list without escaping characters and without interpolations

sigil_R(arg1, options)

Handles the sigil ~R. It returns a Regex pattern without escaping nor interpreting interpolations

sigil_S(string, list2)

Handles the sigil ~S. It simply returns a string without escaping characters and without interpolations

sigil_W(arg1, modifiers)

Handles the sigil ~W. It returns a list of "words" split by whitespace without escaping nor interpreting interpolations

sigil_c(arg1, list2)

Handles the sigil ~c. It returns a char list as if it were a single quoted string, unescaping characters and replacing interpolations

sigil_r(arg1, options)

Handles the sigil ~r. It returns a Regex pattern

sigil_s(arg1, list2)

Handles the sigil ~s. It returns a string as if it was double quoted string, unescaping characters and replacing interpolations

sigil_w(arg1, modifiers)

Handles the sigil ~w. It returns a list of "words" split by whitespace

size(arg)

Returns the size of the given argument, which must be a tuple or a binary

spawn(fun)

Spawns the given function and returns its pid

spawn(module, fun, args)

Spawns the given module and function passing the given args and returns its pid

spawn_link(fun)

Spawns the given function, links it to the current process and returns its pid

spawn_link(module, fun, args)

Spawns the given module and function passing the given args, links it to the current process and returns its pid

throw(term)

A non-local return from a function. Check try/2 for more information

tl(list)

Returns the tail of a list. Raises ArgumentError if the list is empty

to_char_list(arg)

Convert the argument to a list according to the List.Chars protocol

to_string(arg)

Converts the argument to a string according to the String.Chars protocol. This is the function invoked when there is string interpolation

trunc(number)

Returns an integer by truncating the given number

tuple_size(tuple)

Returns the size of a tuple

tuple_to_list(tuple)

Converts a tuple to a list

unless(clause, options)

Evaluates and returns the do-block passed in as a second argument unless clause evaluates to true. Returns nil otherwise. See also if

use(module, args \\ [])

use is a simple mechanism for using a given module into the current context

var!(var, context \\ nil)

When used inside quoting, marks that the variable should not be hygienized. The argument can be either a variable unquoted or an atom representing the variable name

left xor right

Boolean exclusive-or. Arguments must be booleans. Returns true if and only if both arguments are different

left |> right

|> is called the pipeline operator as it is useful to write pipeline style expressions. This operator introduces the expression on the left as the first argument to the function call on the right

left || right

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

Functions

left != right

Specs:

  • term != term :: boolean

Returns true if the two items are not equal.

This operator considers 1 and 1.0 to be equal. For match comparison, use !== instead.

All terms in Elixir can be compared with each other.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 != 2
true
iex> 1 != 1.0
false
Source
left !== right

Specs:

  • term !== term :: boolean

Returns true if the two items do not match.

All terms in Elixir can be compared with each other.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 !== 2
true

iex> 1 !== 1.0
true
Source
left * right

Specs:

  • number * number :: number

Arithmetic multiplication.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 * 2
2
Source
+value

Specs:

  • +number :: number

Arithmetic unary plus.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> +1
1
Source
left + right

Specs:

  • number + number :: number

Arithmetic plus.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 + 2
3
Source
left ++ right

Specs:

  • [] ++ term :: maybe_improper_list

Concatenates two lists.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> [1] ++ [2, 3]
[1,2,3]

iex> 'foo' ++ 'bar'
'foobar'
Source
-value

Specs:

  • -number :: number

Arithmetic unary minus.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> -2
-2
Source
left - right

Specs:

  • number - number :: number

Arithmetic minus.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 - 2
-1
Source
left -- right

Specs:

  • [] -- [] :: []

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

Allowed in guard tests. Inlined by the compiler.

Examples

iex> [1, 2, 3] -- [1, 2]
[3]

iex> [1, 2, 3, 2, 1] -- [1, 2, 2]
[3,1]
Source
left / right

Specs:

  • number / number :: float

Arithmetic division.

The result is always a float. Use div and rem if you want a natural division or the remainder.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 / 2
0.5
iex> 2 / 1
2.0
Source
left < right

Specs:

  • term < term :: boolean

Returns true if left is less than right.

All terms in Elixir can be compared with each other.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 < 2
true
Source
left <= right

Specs:

  • term <= term :: boolean

Returns true if left is less than or equal to right.

All terms in Elixir can be compared with each other.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 <= 2
true
Source
left == right

Specs:

  • term == term :: boolean

Returns true if the two items are equal.

This operator considers 1 and 1.0 to be equal. For match semantics, use === instead.

All terms in Elixir can be compared with each other.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 == 2
false

iex> 1 == 1.0
true
Source
left === right

Specs:

  • term === term :: boolean

Returns true if the two items are match.

This operator gives the same semantics as the one existing in pattern matching, i.e., 1 and 1.0 are equal, but they do not match.

All terms in Elixir can be compared with each other.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 === 2
false

iex> 1 === 1.0
false
Source
left =~ right

Matches the term on the left against the regular expression or string on the right. Returns true if left matches right (if it's a regular expression) or contains right (if it's a string).

Examples

iex> "abcd" =~ ~r/c(d)/
true

iex> "abcd" =~ ~r/e/
false

iex> "abcd" =~ "bc"
true

iex> "abcd" =~ "ad"
false
Source
left > right

Specs:

  • term > term :: boolean

Returns true if left is more than right.

All terms in Elixir can be compared with each other.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 > 2
false
Source
left >= right

Specs:

  • term >= term :: boolean

Returns true if left is more than or equal to right.

All terms in Elixir can be compared with each other.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> 1 >= 2
false
Source
abs(number)

Specs:

  • abs(number) :: number

Returns an integer or float which is the arithmetical absolute value of number.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> abs(-3.33)
3.33
iex> abs(-3)
3
Source
apply(fun, args)

Specs:

  • apply((... -> any), [any]) :: any

Invokes the given fun with the array of arguments args.

Inlined by the compiler.

Examples

iex> apply(fn x -> x * 2 end, [2])
4
Source
apply(module, fun, args)

Specs:

  • apply(module, atom, [any]) :: any

Invokes the given fun from module with the array of arguments args.

Inlined by the compiler.

Examples

iex> apply(Enum, :reverse, [[1, 2, 3]])
[3,2,1]
Source
atom_to_binary(some_atom)

Specs:

  • atom_to_binary(atom) :: binary

Returns a binary which corresponds to the text representation of some_atom in UTF8 encoding.

Inlined by the compiler.

Examples

iex> atom_to_binary(:my_atom)
"my_atom"
Source
atom_to_list(atom)

Specs:

  • atom_to_list(atom) :: char_list

Returns a string which corresponds to the text representation of atom.

Inlined by the compiler.

Examples

iex> atom_to_list(:elixir)
'elixir'
Source
binary_part(binary, start, length)

Specs:

  • binary_part(binary, pos_integer, integer) :: binary

Extracts the part of the binary starting at start with length length. Binaries are zero-indexed.

If start or length references in any way outside the binary, an ArgumentError exception is raised.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> binary_part("foo", 1, 2)
"oo"

A negative length can be used to extract bytes at the end of a binary:

iex> binary_part("foo", 3, -1)
"o"
Source
binary_to_atom(some_binary)

Specs:

  • binary_to_atom(binary) :: atom

Returns the atom whose text representation is some_binary in UTF8 encoding.

Currently Elixir does not support conversions for binaries which contains Unicode characters greater than 16#FF.

Inlined by the compiler.

Examples

iex> binary_to_atom("my_atom")
:my_atom
Source
binary_to_existing_atom(some_binary)

Specs:

  • binary_to_existing_atom(binary) :: atom

Works like binary_to_atom/1 but the atom must exist.

Currently Elixir does not support conversions for binaries which contains Unicode characters greater than 16#FF.

Inlined by the compiler.

Examples

iex> :my_atom
...> binary_to_existing_atom("my_atom")
:my_atom

iex> binary_to_existing_atom("this_atom_will_never_exist")
** (ArgumentError) argument error
Source
binary_to_float(some_binary)

Specs:

  • binary_to_float(binary) :: float

Returns a float whose text representation is some_binary.

Inlined by the compiler.

Examples

iex> binary_to_float("2.2017764e+0")
2.2017764
Source
binary_to_integer(some_binary)

Specs:

  • binary_to_integer(binary) :: integer

Returns a integer whose text representation is some_binary.

Inlined by the compiler.

Examples

iex> binary_to_integer("123")
123
Source
binary_to_integer(some_binary, base)

Specs:

  • binary_to_integer(binary, pos_integer) :: integer

Returns an integer whose text representation in base base is some_binary.

Inlined by the compiler.

Examples

iex> binary_to_integer("3FF", 16)
1023
Source
bit_size(bitstring)

Specs:

  • bit_size(bitstring) :: non_neg_integer

Returns an integer which is the size in bits of bitstring.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> bit_size(<<433::16, 3::3>>)
19
iex> bit_size(<<1, 2, 3>>)
24
Source
bitstring_to_list(bitstring)

Specs:

  • bitstring_to_list(bitstring) :: []

Returns a list of integers which correspond to the bytes of bitstring.

If the number of bits in the binary is not divisible by 8, the last element of the list will be a bitstring containing the remaining bits (1 up to 7 bits).

Inlined by the compiler.

Source
byte_size(bitstring)

Specs:

  • byte_size(bitstring) :: non_neg_integer

Returns an integer which is the number of bytes needed to contain bitstring. (That is, if the number of bits in bitstring is not divisible by 8, the resulting number of bytes will be rounded up.)

Allowed in guard tests. Inlined by the compiler.

Examples

iex> byte_size(<<433::16, 3::3>>)
3
iex> byte_size(<<1, 2, 3>>)
3
Source
div(left, right)

Specs:

  • div(integer, integer) :: integer

Performs an integer division.

Raises an error if one of the arguments is not an integer.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> div(5, 2)
2
Source
elem(tuple, index)

Specs:

  • elem(tuple, non_neg_integer) :: term

Get the element at the zero-based index in tuple.

Allowed in guard tests. Inlined by the compiler.

Example

iex> tuple = { :foo, :bar, 3 }
...> elem(tuple, 1)
:bar
Source
exit(reason)

Specs:

  • exit(term) :: no_return

Stops the execution of the calling process with the given reason.

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

Inlined by the compiler.

Examples

exit(:normal)
exit(:seems_bad)
Source
float_to_binary(some_float)

Specs:

  • float_to_binary(float) :: binary

Returns a binary which corresponds to the text representation of some_float.

Inlined by the compiler.

Examples

iex> float_to_binary(7.0)
"7.00000000000000000000e+00"
Source
float_to_binary(float, options)

Specs:

  • float_to_binary(float, []) :: binary

Returns a binary which corresponds to the text representation of float.

Options

  • :decimals — number of decimal points to show
  • :scientific — number of decimal points to show, in scientific format
  • :compact — when true, use the most compact representation (ignored with the scientific option)

Examples

float_to_binary 7.1, [decimals: 2, compact: true] #=> "7.1"
Source
float_to_list(number)

Specs:

  • float_to_list(float) :: char_list

Returns a char list which corresponds to the text representation of the given float.

Inlined by the compiler.

Examples

iex> float_to_list(7.0)
'7.00000000000000000000e+00'
Source
float_to_list(float, options)

Specs:

  • float_to_list(float, []) :: char_list

Returns a list which corresponds to the text representation of float.

Options

  • :decimals — number of decimal points to show
  • :scientific — number of decimal points to show, in scientific format
  • :compact — when true, use the most compact representation (ignored with the scientific option)

Examples

float_to_list 7.1, [decimals: 2, compact: true] #=> '7.1'
Source
function_exported?(module, function, arity)

Specs:

  • function_exported?(atom | tuple, atom, integer) :: boolean

Returns true if the module is loaded and contains a public function with the given arity, otherwise false.

In case a tuple module is given, the arity is automatically increased by one.

Notice that this function does not load the module in case it is not loaded. Check Code.ensure_loaded/1 for more information.

Source
hd(list)

Specs:

  • hd([]) :: term

Returns the head of a list, raises badarg if the list is empty.

Inlined by the compiler.

Source
inspect(arg, opts \\ [])

Specs:

Inspect the given argument according to the Inspect protocol. The second argument is a keywords list with options to control inspection.

Options

The following options are supported:

  • :records - when false, records are not formatted by the inspect protocol, they are instead printed as just tuples, defaults to true;

  • :binaries - when :as_strings all binaries will be printed as strings, non-printable bytes will be escaped; when :as_binaries all binaries will be printed in bit syntax; when the default :infer, the binary will be printed as a string if it is printable, otherwise in bit syntax;

  • :char_lists - when :as_char_lists all lists will be printed as char lists, non-printable elements will be escaped; when :as_lists all lists will be printed as lists; when the default :infer, the list will be printed as a char list if it is printable, otherwise as list;

  • :limit - limits the number of items that are printed for tuples, bitstrings, and lists, does not apply to strings nor char lists, defaults to 50;

  • :pretty - if set to true enables pretty printing, defaults to false;

  • :width - the width available for inspect to layout the data structure representation. Defaults to the smaller of 80 or the terminal width;

Examples

iex> inspect(:foo)
":foo"

iex> inspect [1, 2, 3, 4, 5], limit: 3
"[1, 2, 3, ...]"

iex> inspect(ArgumentError[])
"ArgumentError[message: \"argument error\"]"

iex> inspect(ArgumentError[], records: false)
"{ArgumentError, :__exception__, \"argument error\"}"

iex> inspect("josé" <> <<0>>)
"<<106, 111, 115, 195, 169, 0>>"

iex> inspect("josé" <> <<0>>, binaries: :as_strings)
"\"josé\\000\""

iex> inspect("josé", binaries: :as_binaries)
"<<106, 111, 115, 195, 169>>"

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 &(&1 + &2)
#=> #Function<...>
Source
integer_to_binary(some_integer)

Specs:

  • integer_to_binary(integer) :: binary

Returns a binary which corresponds to the text representation of some_integer.

Inlined by the compiler.

Examples

iex> integer_to_binary(123)
"123"
Source
integer_to_binary(some_integer, base)

Specs:

  • integer_to_binary(integer, pos_integer) :: binary

Returns a binary which corresponds to the text representation of some_integer in base base.

Inlined by the compiler.

Examples

iex> integer_to_binary(100, 16)
"64"
Source
integer_to_list(number)

Specs:

  • integer_to_list(integer) :: []

Returns a char list which corresponds to the text representation of the given integer.

Inlined by the compiler.

Examples

iex> integer_to_list(7)
'7'
Source
integer_to_list(number, base)

Specs:

  • integer_to_list(integer, pos_integer) :: []

Returns a char list which corresponds to the text representation of the given integer in the given case.

Inlined by the compiler.

Examples

iex> integer_to_list(1023, 16)
'3FF'
Source
iolist_size(item)

Specs:

  • iolist_size(iolist) :: non_neg_integer

Returns the size of an iolist.

Inlined by the compiler.

Examples

iex> iolist_size([1, 2|<<3, 4>>])
4
Source
iolist_to_binary(item)

Specs:

  • iolist_to_binary(iolist | binary) :: binary

Returns a binary which is made from the integers and binaries in iolist.

Notice that this function treats lists of integers as raw bytes and does not perform any kind of encoding conversion. If you want to convert from a char list to a string (both utf-8 encoded), please use String.from_char_list!/1 instead.

If this function receives a binary, the same binary is returned.

Inlined by the compiler.

Examples

iex> bin1 = <<1, 2, 3>>
...> bin2 = <<4, 5>>
...> bin3 = <<6>>
...> iolist_to_binary([bin1, 1, [2, 3, bin2], 4|bin3])
<<1,2,3,1,2,3,4,5,4,6>>

iex> bin = <<1, 2, 3>>
...> iolist_to_binary(bin)
<<1,2,3>>
Source
is_atom(term)

Specs:

  • is_atom(term) :: boolean

Returns true if term is an atom; otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_binary(term)

Specs:

  • is_binary(term) :: boolean

Returns true if term is a binary; otherwise returns false.

A binary always contains a complete number of bytes.

Allowed in guard tests. Inlined by the compiler.

Source
is_bitstring(term)

Specs:

  • is_bitstring(term) :: boolean

Returns true if term is a bitstring (including a binary); otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_boolean(term)

Specs:

  • is_boolean(term) :: boolean

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.

Source
is_float(term)

Specs:

  • is_float(term) :: boolean

Returns true if term is a floating point number; otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_function(term)

Specs:

  • is_function(term) :: boolean

Returns true if term is a function; otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_function(term, arity)

Specs:

  • is_function(term, non_neg_integer) :: boolean

Returns true if term is a function that can be applied with arity number of arguments; otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_integer(term)

Specs:

  • is_integer(term) :: boolean

Returns true if term is an integer; otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_list(term)

Specs:

  • is_list(term) :: boolean

Returns true if term is a list with zero or more elements; otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_number(term)

Specs:

  • is_number(term) :: boolean

Returns true if term is either an integer or a floating point number; otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_pid(term)

Specs:

  • is_pid(term) :: boolean

Returns true if term is a pid (process identifier); otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_port(term)

Specs:

  • is_port(term) :: boolean

Returns true if term is a port identifier; otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_reference(term)

Specs:

  • is_reference(term) :: boolean

Returns true if term is a reference; otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
is_tuple(term)

Specs:

  • is_tuple(term) :: boolean

Returns true if term is a tuple; otherwise returns false.

Allowed in guard tests. Inlined by the compiler.

Source
length(list)

Specs:

  • length([]) :: non_neg_integer

Returns the length of list.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9])
9
Source
list_to_atom(list)

Specs:

  • list_to_atom(char_list) :: atom

Returns the atom whose text representation is list.

Inlined by the compiler.

Examples

iex> list_to_atom('elixir')
:elixir
Source
list_to_bitstring(bitstring_list)

Specs:

  • list_to_bitstring(maybe_improper_list(char | binary | iolist | bitstring, binary | bitstring | nil)) :: bitstring

Returns a bitstring which is made from the integers and bitstrings in bitstring_list. (the last tail in bitstring_list is allowed to be a bitstring.)

Inlined by the compiler.

Examples

iex> bin1 = <<1, 2, 3>>
...> bin2 = <<4, 5>>
...> bin3 = <<6, 7::4>>
...> list_to_bitstring([bin1, 1, [2, 3, bin2], 4|bin3])
<<1,2,3,1,2,3,4,5,4,6,7::size(4)>>
Source
list_to_existing_atom(list)

Specs:

  • list_to_existing_atom([]) :: atom

Returns the atom whose text representation is list, but only if there already exists such atom.

Inlined by the compiler.

Source
list_to_float(list)

Specs:

  • list_to_float([]) :: float

Returns the float whose text representation is list.

Inlined by the compiler.

Examples

iex> list_to_float('2.2017764e+0')
2.2017764
Source
list_to_integer(list)

Specs:

  • list_to_integer([]) :: integer

Returns an integer whose text representation is list.

Inlined by the compiler.

Examples

iex> list_to_integer('123')
123
Source
list_to_integer(list, base)

Specs:

  • list_to_integer([], non_neg_integer) :: integer

Returns an integer whose text representation in base base is list.

Inlined by the compiler.

Examples

iex> list_to_integer('3FF', 16)
1023
Source
list_to_tuple(list)

Specs:

  • list_to_tuple([]) :: tuple

Returns a tuple which corresponds to list. list can contain any Erlang terms.

Inlined by the compiler.

Examples

iex> list_to_tuple([:share, [:elixir, 163]])
{:share, [:elixir, 163]}
Source
macro_exported?(module, macro, arity)

Specs:

  • macro_exported?(atom, atom, integer) :: boolean

Returns true if the module is loaded and contains a public macro with the given arity, otherwise false.

Notice that this function does not load the module in case it is not loaded. Check Code.ensure_loaded/1 for more information.

Source
make_ref()

Specs:

  • make_ref :: reference

Returns an almost unique reference.

The returned reference will re-occur after approximately 2^82 calls; therefore it is unique enough for practical purposes.

Inlined by the compiler.

Examples

make_ref() #=> #Reference<0.0.0.135>
Source
max(first, second)

Specs:

  • max(term, term) :: term

Return 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)
2
Source
min(first, second)

Specs:

  • min(term, term) :: term

Return 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)
1
Source
node()

Specs:

  • node :: node

Returns an atom representing the name of the local node. If the node is not alive, :nonode@nohost is returned instead.

Allowed in guard tests. Inlined by the compiler.

Source
node(arg)

Specs:

  • node(pid | reference | port) :: node

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.

Allowed in guard tests. Inlined by the compiler.

Source
not arg

Specs:

  • not boolean :: boolean

Boolean not. Argument must be a boolean.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> not false
true
Source
rem(left, right)

Specs:

  • rem(integer, integer) :: integer

Calculates the remainder of an integer division.

Raises an error if one of the arguments is not an integer.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> rem(5, 2)
1
Source
round(number)

Specs:

  • round(number) :: integer

Returns an integer by rounding the given number.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> round(5.5)
6
Source
self()

Specs:

  • self :: pid

Returns the pid (process identifier) of the calling process.

Allowed in guard clauses. Inlined by the compiler.

Source
send(dest, msg)

Specs:

  • send(dest :: pid | port | atom | {atom, node}, msg) :: msg when msg: any

Sends a message to the given dest and returns the message.

dest may be a remote or local pid, a (local) port, a locally registered name, or a tuple {registed_name, node} for a registered name at another node.

Inlined by the compiler.

Examples

iex> send self(), :hello
:hello
Source
set_elem(tuple, index, value)

Specs:

  • set_elem(tuple, non_neg_integer, term) :: tuple

Sets the element in tuple at the zero-based index to the given value.

Inlined by the compiler.

Example

iex> tuple = { :foo, :bar, 3 }
...> set_elem(tuple, 0, :baz)
{ :baz, :bar, 3 }
Source
size(arg)

Specs:

  • size(tuple | binary) :: non_neg_integer

Returns the size of the given argument, which must be a tuple or a binary.

Prefer using tuple_size or byte_size insted.

Allowed in guard tests. Inlined by the compiler.

Source
spawn(fun)

Specs:

  • spawn((() -> any)) :: pid

Spawns the given function and returns its pid.

Check the modules Process and Node for other functions to handle processes, including spawning functions in nodes.

Inlined by the compiler.

Examples

current = Kernel.self
child   = spawn(fn -> send current, { Kernel.self, 1 + 2 } end)

receive do
  { ^child, 3 } -> IO.puts "Received 3 back"
end
Source
spawn(module, fun, args)

Specs:

  • spawn(module, atom, []) :: pid

Spawns the given module and function passing the given args and returns its pid.

Check the modules Process and Node for other functions to handle processes, including spawning functions in nodes.

Inlined by the compiler.

Examples

spawn(SomeModule, :function, [1, 2, 3])
Source
spawn_link(fun)

Specs:

  • spawn_link((() -> any)) :: pid

Spawns the given function, links it to the current process and returns its pid.

Check the modules Process and Node for other functions to handle processes, including spawning functions in nodes.

Inlined by the compiler.

Examples

current = Kernel.self
child   = spawn_link(fn -> send current, { Kernel.self, 1 + 2 } end)

receive do
  { ^child, 3 } -> IO.puts "Received 3 back"
end
Source
spawn_link(module, fun, args)

Specs:

  • spawn_link(module, atom, []) :: pid

Spawns the given module and function passing the given args, links it to the current process and returns its pid.

Check the modules Process and Node for other functions to handle processes, including spawning functions in nodes.

Inlined by the compiler.

Examples

spawn_link(SomeModule, :function, [1, 2, 3])
Source
throw(term)

Specs:

  • throw(term) :: no_return

A non-local return from a function. Check try/2 for more information.

Inlined by the compiler.

Source
tl(list)

Specs:

  • tl(maybe_improper_list) :: maybe_improper_list

Returns the tail of a list. Raises ArgumentError if the list is empty.

Allowed in guard tests. Inlined by the compiler.

Source
trunc(number)

Specs:

  • trunc(number) :: integer

Returns an integer by truncating the given number.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> trunc(5.5)
5
Source
tuple_size(tuple)

Specs:

  • tuple_size(tuple) :: non_neg_integer

Returns the size of a tuple.

Allowed in guard tests. Inlined by the compiler.

Source
tuple_to_list(tuple)

Specs:

  • tuple_to_list(tuple) :: []

Converts a tuple to a list.

Inlined by the compiler.

Source
left xor right

Specs:

  • boolean xor boolean :: boolean

Boolean exclusive-or. Arguments must be booleans. Returns true if and only if both arguments are different.

Allowed in guard tests. Inlined by the compiler.

Examples

iex> true xor false
true
iex> true xor true
false
Source

Macros

!arg

Receives any argument and returns true if it is false or nil. Returns false otherwise. Not allowed in guard clauses.

Examples

iex> !Enum.empty?([])
false
iex> !List.first([])
true
Source
left && right

Provides a short-circuit operator that evaluates and returns the second expression only if the first one evaluates to true (i.e. it is not nil nor false). Returns the first expression otherwise.

Examples

iex> Enum.empty?([]) && Enum.empty?([])
true

iex> List.first([]) && true
nil

iex> Enum.empty?([]) && List.first([1])
1

iex> false && throw(:bad)
false

Notice that, unlike Erlang's and operator, this operator accepts any expression as an argument, not only booleans, however it is not allowed in guards.

Source
first .. last

Returns a range with the specified start and end. Includes both ends.

Examples

iex> 0 in 1..3
false
iex> 1 in 1..3
true
iex> 2 in 1..3
true
iex> 3 in 1..3
true
Source
left <> right

Concatenates two binaries.

Examples

iex> "foo" <> "bar"
"foobar"

The <> operator can also be used in guard clauses as long as the first part is a literal binary:

iex> "foo" <> x = "foobar"
...> x
"bar"
Source
@expr

This macro is a shortcut to read and add attributes to the module being compiled. Elixir module attributes are similar to Erlang's with some differences. The canonical example for attributes is annotating that a module implements the OTP behaviour called gen_server:

defmodule MyServer do
  @behaviour :gen_server
  # ... callbacks ...
end

By default Elixir supports all Erlang module attributes, but any developer can also add custom attributes:

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 such attributes to store temporary data. A developer can configure an attribute to behave closer to Erlang by calling Module.register_attribute/3.

Finally, notice that attributes can also be read inside functions:

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

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.

Source
access(element, args)

Access the given element using the qualifier according to the Access protocol. All calls in the form foo[bar] are translated to access(foo, bar).

The usage of this protocol is to access a raw value in a keyword list.

sample = [a: 1, b: 2, c: 3]
sample[:b] #=> 2

Aliases

Whenever invoked on an alias or an atom, the access protocol is expanded at compilation time rather than on runtime. This feature is used by records to allow a developer to match against an specific part of a record:

def increment(State[counter: counter, other: 13] = state) do
  state.counter(counter + 1)
end

In the example above, we use the Access protocol to match the counter field in the record State. Considering the record definition is as follows:

defrecord State, counter: 0, other: nil

The clause above is translated to:

def increment({ State, counter, 13 } = state) do
  state.counter(counter + 1)
end

The same pattern can be used to create a new record:

def new_state(counter) do
  State[counter: counter]
end

The example above is faster than State.new(counter: :counter) because the record is expanded at compilation time and not at runtime. If a field is not specified on creation, it will have its default value.

Finally, as in Erlang, Elixir also allows the following syntax:

new_uri = State[_: 1]

In this case all fields will be set to 1. Notice that, as in Erlang, in case an expression is given, it will be evaluated multiple times:

new_uri = State[_: IO.puts "Hello"]

In this case, "Hello" will be printed twice (one per each field).

Source
alias!(alias)

When used inside quoting, marks that the alias should not be hygienezed. This means the alias will be expanded when the macro is expanded.

Check Kernel.SpecialForms.quote/2 for more information.

Source
left and right

Boolean and. Requires only the first argument to be a boolean since it short-circuits.

Allowed in guard tests.

Examples

iex> true and false
false
Source
binding()

Returns the binding as a keyword list where the variable name is the key and the variable value is the value.

Examples

iex> x = 1
iex> binding()
[x: 1]
iex> x = 2
iex> binding()
[x: 2]
Source
binding(list)

Receives a list of atoms at compilation time and returns the binding of the given variables as a keyword list where the variable name is the key and the variable value is the value.

In case a variable in the list does not exist in the binding, it is not included in the returned result.

Examples

iex> x = 1
iex> binding([:x, :y])
[x: 1]
Source
binding(list, context)

Receives a list of atoms at compilation time and returns the binding of the given variables in the given context as a keyword list where the variable name is the key and the variable value is the value.

In case a variable in the list does not exist in the binding, it is not included in the returned result.

Examples

iex> var!(x, :foo) = 1
iex> binding([:x, :y])
[]
iex> binding([:x, :y], :foo)
[x: 1]
Source
cond(list1)

Evaluates the expression corresponding to the first clause that evaluates to true. Raises an error if all conditions evaluate to to nil or false.

Examples

cond do
  1 + 1 == 1 ->
    "This will never match"
  2 * 2 != 4 ->
    "Nor this"
  true ->
    "This will"
end
Source
def(call, expr \\ nil)

Defines a function with the given name and contents.

Examples

defmodule Foo do
  def bar, do: :baz
end

Foo.bar #=> :baz

A function that expects arguments can be defined as follow:

defmodule Foo do
  def sum(a, b) do
    a + b
  end
end

In the example above, we defined a function sum that receives two arguments and sums them.

Source
defdelegate(funs, opts)

Defines the given functions in the current module that will delegate to the given target. Functions defined with defdelegate are public and are allowed to be invoked from external. If you find yourself wishing to define a delegation as private, you should likely use import instead.

Delegation only works with functions, delegating to macros is not supported.

Options

  • :to - The expression to delegate to. Any expression is allowed and its results will be calculated on runtime;

  • :as - The function to call on the target given in :to. This parameter is optional and defaults to the name being delegated.

  • :append_first - If true, when delegated, first argument passed to the delegate will be relocated to the end of the arguments when dispatched to the target. The motivation behind this is because Elixir normalizes the "handle" as a first argument and some Erlang modules expect it as last argument.

Examples

defmodule MyList do
  defdelegate reverse(list), to: :lists
  defdelegate [reverse(list), map(callback, list)], to: :lists
  defdelegate other_reverse(list), to: :lists, as: :reverse
end

MyList.reverse([1, 2, 3])
#=> [3,2,1]

MyList.other_reverse([1, 2, 3])
#=> [3,2,1]
Source
defexception(name, fields, do_block \\ [])

Defines an exception.

Exceptions are simply records with three differences:

  1. Exceptions are required to define a function exception/1 that receives keyword arguments and returns the exception. This function is a callback usually invoked by raise/2;

  2. Exceptions are required to provide a message field. This field must return a String with a formatted error message;

  3. Unlike records, exceptions are documented by default.

Since exceptions are records, defexception/3 has exactly the same API as defrecord/3.

Raising exceptions

The most common way to raise an exception is via the raise/2 function:

defexception MyException, [:message]
raise MyException,
  message: "did not get what was expected, got: #{inspect value}"

In many cases it is more convenient to pass the expected value to raise and generate the message in the exception/1 callback:

defexception MyException, [:message] do
  def exception(opts) do
    msg = "did not get what was expected, got: #{inspect opts[:actual]}"
    MyException[message: msg]
  end
end

raise MyException, actual: value

The example above is the preferred mechanism for customizing exception messages.

Source
defimpl(name, opts, do_block \\ [])

Defines an implementation for the given protocol. See defprotocol/2 for examples.

Inside an implementation, the name of the protocol can be accessed via @protocol and the current target as @for.

Source
defmacro(call, expr \\ nil)

Defines a macro with the given name and contents.

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
Source
defmacrop(call, expr \\ nil)

Defines a macro that is private. Private macros are only accessible from the same module in which they are defined.

Check defmacro/2 for more information

Source
defmodule(alias, list2)

Defines a module given by name with the given contents.

It returns the module name, the module binary and the block contents result.

Examples

defmodule Foo do
  def bar, do: :baz
end

Foo.bar #=> :baz

Nesting

Nesting a module inside another module affects its name:

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, allowing the second module Foo.Bar to be accessed as Bar in the same lexical scope.

This means that, if the module Bar is moved to another file, the references to Bar needs to be updated or an alias needs to be explicitly set with the help of Kernel.SpecialForms.alias/2.

Dynamic names

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

defmodule binary_to_atom("Foo#{1}") do
  # contents ...
end

Elixir will accept any module name as long as the expression returns 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.

Source
defoverridable(tuples)

Makes the given functions in the current module overridable. An overridable function is lazily defined, allowing a developer to customize it.

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 super can be used to call the default implementation.

Source
defp(call, expr \\ nil)

Defines a function that is private. Private functions are only accessible from within the module in which they are defined.

Check def/2 for more information

Examples

defmodule Foo do
  def bar do
    sum(1, 2)
  end

  defp sum(a, b), do: a + b
end

In the example above, sum is private and accessing it through Foo.sum will raise an error.

Source
defprotocol(name, list2)

Defines a module as a protocol and specifies the API that should be defined by its implementations.

Examples

In Elixir, only false and nil are considered falsy values. Everything else evaluates to true in if clauses. Depending on the application, it may be important to specify a blank? protocol that returns a boolean for other data types that should be considered blank?. For instance, an empty list or an empty binary could be considered blanks.

We could implement this protocol as follow:

defprotocol Blank do
  @doc "Returns true if data is considered blank/empty"
  def blank?(data)
end

Now that the protocol is defined, we can implement it. We need to implement the protocol for each Elixir type. For example:

# Integers are never blank
defimpl Blank, for: Integer do
  def blank?(number), do: false
end

# Just empty list is blank
defimpl Blank, for: List do
  def blank?([]), do: true
  def blank?(_),  do: false
end

# Just the atoms false and nil are blank
defimpl Blank, for: Atom do
  def blank?(false), do: true
  def blank?(nil),   do: true
  def blank?(_),     do: false
end

And we would have to define the implementation for all types. The supported types available are:

  • Record (see below)
  • Tuple
  • Atom
  • List
  • BitString
  • Integer
  • Float
  • Function
  • PID
  • Port
  • Reference
  • Any (see below)

Protocols + Records

The real benefit of protocols comes when mixed with records. For instance, Elixir ships with many data types implemented as records, like HashDict and HashSet. We can implement the Blank protocol for those types as well:

defimpl Blank, for: HashDict do
  def blank?(dict), do: Dict.empty?(dict)
end

Since records are tuples, if a protocol is not found a given type, it will fallback to Tuple.

Fallback to any

In some cases, it may be convenient to provide a default implementation for all types. This can be achieved by setting @fallback_to_any to true in the protocol definition:

defprotocol Blank do
  @fallback_to_any true
  def blank?(data)
end

Which can now be implemented as:

defimpl Blank, for: Any do
  def blank?(_), do: true
end

One may wonder why such fallback is not true by default.

It is two-fold: first, the majority of protocols cannot implement an action in a generic way for all types. In fact, providing a default implementation may be harmful, because users may rely on the default implementation instead of providing a specialized one.

Second, falling back to Any adds an extra lookup to all types, which is unnecessary overhead unless an implementation for Any is required.

Types

As in records, defining a protocol automatically defines a type named t, which can be used as:

@spec present?(Blank.t) :: boolean
def present?(blank) do
  not Blank.blank?(blank)
end

The @spec above expresses that all types allowed to implement the given protocol are valid argument types for the given function.

Reflection

Any protocol module contains three extra functions:

  • __protocol__/1 - returns the protocol name when :name is given, and a keyword list with the protocol functions when :functions is given;

  • impl_for/1 - receives a structure and returns the module that implements the protocol for the structure, nil otherwise;

  • impl_for!/1 - same as above but raises an error if an implementation is not found

Consolidation

In order to cope with code loading in development, protocols in Elixir provide a slow implementation of protocol dispatching in development.

In order to speed up dispatching in production environments, where all implementations are now up-front, Elixir provides a feature called protocol consolidation. For this reason, all protocols are compiled with debug_info set to true, regardless of the option set by elixirc compiler.

For more information on how to apply protocol consolidation to a given project, please check the mix compile.protocols task.

Source
defrecord(name, fields, do_block \\ [])

Exports a module with a record definition and runtime operations.

Please see the Record module's documentation for an introduction to records in Elixir. The following sections are going into details specific to defrecord.

Examples

defrecord User, name: nil, age: 0

The following line defines a module that exports information about a record. The definition above provides a shortcut syntax for creating and updating the record at compilation time:

user = User[]
#=> User[name: nil, age: 0]

User[name: "José", age: 25]
#=> User[name: "José", age: 25]

And also a set of functions for working with the record at runtime:

user = User.new(age: 25)
user.name          #=> Returns the value of name
user.name("José")  #=> Updates the value of name

# Update multiple attributes at once:
user.update(name: "Other", age: 25)

# Obtain the keywords representation of a record:
user.to_keywords #=> [name: "José", age: 25]

Since a record is simply a tuple where the first element is the record name, we can get the raw record representation as follows:

inspect User.new, records: false
#=> { User, nil, 0 }

In addition to defining readers and writers for each attribute, Elixir also defines an update_#{attribute} function to update the value. Such functions expect a function as an argument that receives the current value and must return the new one. For example, every time the file is accessed, the accesses counter can be incremented with:

user.update_age(fn(old) -> old + 1 end)

Types

Every record defines a type named t that can be accessed in typespecs. Those types can be specified inside the record definition:

defrecord User do
  record_type name: string, age: integer
end

All fields without a specified type are assumed to have type term.

Assuming the User record defined above, it could be used in typespecs as follow:

@spec handle_user(User.t) :: boolean()

Runtime introspection

At runtime, developers can use __record__ to get information about the given record:

User.__record__(:name)
#=> User

User.__record__(:fields)
#=> [name: nil, age: 0]

In order to quickly access the index of a field, one can use the __record__ function with :index as the first argument:

User.__record__(:index, :age)
#=> 2

User.__record__(:index, :unknown)
#=> nil

Compile-time introspection

At compile time, one can access the following information about the record from within the record module:

  • @record_fields — a keyword list of record fields with defaults
  • @record_types — a keyword list of record fields with types

For example:

defrecord Foo, bar: nil do
  record_type bar: nil | integer
  IO.inspect @record_fields
  IO.inspect @record_types
end

Prints out:

 [bar: nil]
 [bar: {:|,[line: ...],[nil,{:integer,[line: ...],nil}]}]

Where the last line is a quoted representation of

 [bar: nil | integer]
Source
defrecordp(name, tag \\ nil, fields)

Defines a set of private macros to manipulate a record definition.

This macro defines a set of macros private to the current module to manipulate the record exclusively at compilation time.

Please see the Record module's documentation for an introduction to records in Elixir.

Examples

defmodule User do
  defrecordp :user, [name: "José", age: "25"]
end

In the example above, a set of macros named user but with different arities will be defined to manipulate the underlying record:

# To create records
user()        #=> { :user, "José", 25 }
user(age: 26) #=> { :user, "José", 26 }

# To get a field from the record
user(record, :name) #=> "José"

# To update the record
user(record, age: 26) #=> { :user, "José", 26 }

By default, Elixir uses the record name as the first element of the tuple. In some cases though, this might be undesirable and one can explicitly define what the first element of the record should be:

defmodule MyServer do
  defrecordp :state, MyServer, data: nil
end

This way, the record created will have MyServer as the first element, not :state:

state() #=> { MyServer, nil }

Types

defrecordp allows a developer to generate a type automatically by simply providing a type to its fields. The following definition:

defrecordp :user,
  name: "José" :: binary,
  age: 25 :: integer

Will generate the following type:

@typep user_t :: { :user, binary, integer }
Source
destructure(left, right)

Allows you to destructure two lists, assigning each term in the right to the matching term in the left. 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

iex> destructure([x, y, z], [1, 2, 3, 4, 5])
...> {x, y, z}
{1, 2, 3}

Notice in the example above, even though the right size has more entries than the left, destructuring works fine. If the right size is smaller, the remaining items are simply assigned to nil:

iex> destructure([x, y, z], [1])
...> {x, y, z}
{1, nil, nil}

The left side supports any expression you would use on the left 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 from the right side. Otherwise, it will raise a CaseClauseError.

Source
if(condition, clauses)

Provides an if macro. This macro expects the first argument to be a condition and the rest are keyword arguments.

One-liner examples

if(foo, do: bar)

In the example above, bar will be returned if foo evaluates to true (i.e. it is neither false nor nil). Otherwise, nil will be returned.

An else option can be given to specify the opposite:

if(foo, do: bar, else: baz)

Blocks examples

Elixir also allows you to pass a block to the if macro. The first example above would be translated to:

if foo do
  bar
end

Notice that do/end becomes delimiters. The second example would then translate to:

if foo do
  bar
else
  baz
end

If you want to compare more than two clauses, you can use the cond/1 macro.

Source
left in right

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

Examples

iex> x = 1
...> x in [1, 2, 3]
true

This macro simply translates the expression above to:

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

Guards

The in operator can be used on guard clauses as long as the right side is a range or a list. Elixir will then expand the operator to a valid guard expression. For example:

when x in [1,2,3]

Translates to:

when x === 1 or x === 2 or x === 3

When using ranges:

when x in 1..3

Translates to:

when x >= 1 and x <= 3
Source
is_exception(thing)

Checks if the given structure is an exception.

Examples

iex> is_exception((fn -> ArithmeticError.new end).())
true
iex> is_exception((fn -> 1 end).())
false
Source
is_range(thing)

Checks if the given argument is a range.

Works in guard clauses.

Source
is_record(thing)

Checks if the given argument is a record.

Source
is_record(thing, kind)

Checks if the given structure is a record. It is basically a convenient macro that checks the structure is a tuple and the first element matches the given kind.

Examples

defrecord Config, sample: nil

is_record(Config.new, Config) #=> true
is_record(Config.new, List)   #=> false
Source
is_regex(thing)

Checks if the given argument is a regex.

Works in guard clauses.

Source
match?(pattern, expr)

A convenient macro that checks if the right side matches the left side. The left side is allowed to be a match pattern.

Examples

iex> match?(1, 1)
true
iex> match?(1, 2)
false
iex> match?({1, _}, {1, 2})
true

Match can also be used to filter or find a value in an enumerable:

list = [{:a, 1}, {:b, 2}, {:a, 3}]
Enum.filter list, &match?({:a, _}, &1)

Guard clauses can also be given to the match:

list = [{:a, 1}, {:b, 2}, {:a, 3}]
Enum.filter list, &match?({:a, x } when x < 2, &1)

However, variables assigned in the match will not be available outside of the function call:

iex> match?(x, 1)
true
iex> binding([:x]) == []
true
Source
nil?(x)

Checks if the given argument is nil or not. Allowed in guard clauses.

Examples

iex> nil?(1)
false
iex> nil?(nil)
true
Source
left or right

Boolean or. Requires only the first argument to be a boolean since it short-circuits.

Allowed in guard tests.

Examples

iex> true or false
true
Source
raise(msg)

Raises an error.

If the argument is a binary, it raises RuntimeError using the given argument as message.

If anything else, becomes a call to raise(argument, []).

Examples

raise "Given values do not match"

try do
  1 + :foo
rescue
  x in [ArithmeticError] ->
    IO.puts "that was expected"
    raise x
end
Source
raise(exception, args)

Raises an error.

Calls .exception on the given argument passing the args in order to retrieve the appropriate exception structure.

Any module defined via defexception automatically implements exception(args) callback expected by raise/2.

Examples

iex> raise(ArgumentError, message: "Sample")
** (ArgumentError) Sample
Source
raise(exception, args, stacktrace)

Re-raises an exception with the given stacktrace.

Examples

try do
  raise "Oops"
rescue
  exception ->
    stacktrace = System.stacktrace
    if exception.message == "Oops" do
      raise exception, [], stacktrace
    end
end

Notice that System.stacktrace returns the stacktrace of the last exception. That said, it is common to assign the stacktrace as the first expression inside a rescue clause as any other exception potentially raised (and rescued) in between the rescue clause and the raise call may change the System.stacktrace value.

Source
sigil_C(arg1, list2)

Handles the sigil ~C. It simply returns a char list without escaping characters and without interpolations.

Examples

iex> ~C(foo)
'foo'
iex> ~C(f#{o}o)
'f\#{o}o'
Source
sigil_R(arg1, options)

Handles the sigil ~R. It returns a Regex pattern without escaping nor interpreting interpolations.

Examples

iex> Regex.match?(~R(f#{1,3}o), "f#o")
true
Source
sigil_S(string, list2)

Handles the sigil ~S. It simply returns a string without escaping characters and without interpolations.

Examples

iex> ~S(foo)
"foo"
iex> ~S(f#{o}o)
"f\#{o}o"
Source
sigil_W(arg1, modifiers)

Handles the sigil ~W. It returns a list of "words" split by whitespace without escaping nor interpreting interpolations.

Modifiers

  • s: strings (default)
  • a: atoms
  • c: char lists

Examples

iex> ~W(foo #{bar} baz)
["foo", "\#{bar}", "baz"]
Source
sigil_c(arg1, list2)

Handles the sigil ~c. It returns a char list as if it were a single quoted string, unescaping characters and replacing interpolations.

Examples

iex> ~c(foo)
'foo'
iex> ~c(f#{:o}o)
'foo'
Source
sigil_r(arg1, options)

Handles the sigil ~r. It returns a Regex pattern.

Examples

iex> Regex.match?(~r(foo), "foo")
true
Source
sigil_s(arg1, list2)

Handles the sigil ~s. It returns a string as if it was double quoted string, unescaping characters and replacing interpolations.

Examples

iex> ~s(foo)
"foo"
iex> ~s(f#{:o}o)
"foo"
Source
sigil_w(arg1, modifiers)

Handles the sigil ~w. It returns a list of "words" split by whitespace.

Modifiers

  • s: strings (default)
  • a: atoms
  • c: char lists

Examples

iex> ~w(foo #{:bar} baz)
["foo", "bar", "baz"]
iex> ~w(--source test/enum_test.exs)
["--source", "test/enum_test.exs"]
iex> ~w(foo bar baz)a
[:foo, :bar, :baz]
Source
to_char_list(arg)

Convert the argument to a list according to the List.Chars protocol.

Examples

iex> to_char_list(:foo)
'foo'
Source
to_string(arg)

Converts the argument to a string according to the String.Chars protocol. This is the function invoked when there is string interpolation.

Examples

iex> to_string(:foo)
"foo"
Source
unless(clause, options)

Evaluates and returns the do-block passed in as a second argument unless clause evaluates to true. Returns nil otherwise. See also if.

Examples

iex> unless(Enum.empty?([]), do: "Hello")
nil
iex> unless(Enum.empty?([1,2,3]), do: "Hello")
"Hello"
Source
use(module, args \\ [])

use is a simple mechanism for using a given module into the current context.

Examples

For example, in order to write tests using the ExUnit framework, a developer should use the ExUnit.Case module:

defmodule AssertionTest do
  use ExUnit.Case, async: true

  def test_always_pass do
    true = true
  end
end

By calling use, a hook called __using__ will be invoked in ExUnit.Case which will then do the proper setup.

Simply put, use is simply a translation to:

defmodule AssertionTest do
  require ExUnit.Case
  ExUnit.Case.__using__([async: true])

  def test_always_pass do
    true = true
  end
end
Source
var!(var, context \\ nil)

When used inside quoting, marks that the variable should not be hygienized. The argument can be either a variable unquoted or an atom representing the variable name.

Check Kernel.SpecialForms.quote/2 for more information.

Source
left |> right

|> is called the pipeline operator as it is useful to write pipeline style expressions. This operator introduces the expression on the left as the first argument to the function call on the right.

Examples

iex> [1, [2], 3] |> List.flatten |> Enum.map(&(&1 * 2))
[2,4,6]

The expression above is simply translated to:

Enum.map(List.flatten([1, [2], 3]), &(&1 * 2))

Be aware of operator precedence when using this operator. For example, the following expression:

String.graphemes "Hello" |> Enum.reverse

Is translated to:

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

Which will result in an error as Enumerable protocol is not defined for binaries. Adding explicit parenthesis resolves the ambiguity:

String.graphemes("Hello") |> Enum.reverse
Source
left || right

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

Examples

iex> Enum.empty?([1]) || Enum.empty?([1])
false

iex> List.first([]) || true
true

iex> Enum.empty?([1]) || 1
1

iex> Enum.empty?([]) || throw(:bad)
true

Notice that, unlike Erlang's or operator, this operator accepts any expression as an argument, not only booleans, however it is not allowed in guards.

Source