On this page
Kernel
Kernel is Elixir's default environment.
It mainly consists of:
- basic language primitives, such as arithmetic operators, spawning of processes, data type handling, and others
- macros for control-flow and defining new functionality (modules, functions, and the like)
- guard checks for augmenting pattern matching
You can invoke Kernel functions and macros anywhere in Elixir code without the use of the Kernel. prefix since they have all been automatically imported. For example, in IEx, you can call:
iex> is_number(13)
true
If you don't want to import a function or macro from Kernel, use the :except option and then list the function/macro by arity:
import Kernel, except: [if: 2, unless: 2]
See Kernel.SpecialForms.import/2 for more information on importing.
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).
Built-in types
The following modules handle Elixir built-in data types:
Atom- literal constants with a name (true,false, andnilare atoms)Float- numbers with floating point precisionFunction- a reference to code chunk, created with thefn/1special formInteger- whole numbers (not fractions)List- collections of a variable number of elements (linked lists)Map- collections of key-value pairsProcess- light-weight threads of executionPort- mechanisms to interact with the external worldTuple- collections of a fixed number of elements
There are two data types without an accompanying module:
- Bitstring - a sequence of bits, created with
Kernel.SpecialForms.<<>>/1. When the number of bits is divisible by 8, they are called binaries and can be manipulated with Erlang's:binarymodule - Reference - a unique value in the runtime system, created with
make_ref/0
Data types
Elixir also provides other data types that are built on top of the types listed above. Some of them are:
Date-year-month-daystructs in a given calendarDateTime- date and time with time zone in a given calendarException- data raised from errors and unexpected scenariosMapSet- unordered collections of unique elementsNaiveDateTime- date and time without time zone in a given calendarKeyword- lists of two-element tuples, often representing optional valuesRange- inclusive ranges between two integersRegex- regular expressionsString- UTF-8 encoded binaries representing charactersTime-hour:minute:secondstructs in a given calendarURI- representation of URIs that identify resourcesVersion- representation of versions and requirements
System modules
Modules that interface with the underlying system, such as:
IO- handles input and outputFile- interacts with the underlying file systemPath- manipulates file system pathsSystem- reads and writes system information
Protocols
Protocols add polymorphic dispatch to Elixir. They are contracts implementable by data types. See Protocol for more information on protocols. Elixir provides the following protocols in the standard library:
Collectable- collects data into a data typeEnumerable- handles collections in Elixir. TheEnummodule provides eager functions for working with collections, theStreammodule provides lazy functionsInspect- converts data types into their programming language representationList.Chars- converts data types to their outside world representation as charlists (non-programming based)String.Chars- converts data types to their outside world representation as strings (non-programming based)
Process-based and application-centric functionality
The following modules build on top of processes to provide concurrency, fault-tolerance, and more.
Agent- a process that encapsulates mutable stateApplication- functions for starting, stopping and configuring applicationsGenServer- a generic client-server APIRegistry- a key-value process-based storageSupervisor- a process that is responsible for starting, supervising and shutting down other processesTask- a process that performs computationsTask.Supervisor- a supervisor for managing tasks exclusively
Supporting documents
Elixir documentation also includes supporting documents under the "Pages" section. Those are:
- Compatibility and deprecations - lists compatibility between every Elixir version and Erlang/OTP, release schema; lists all deprecated functions, when they were deprecated and alternatives
- Library guidelines - general guidelines, anti-patterns, and rules for those writing libraries
- Naming conventions - naming conventions for Elixir code
- Operators - lists all Elixir operators and their precedences
- Patterns and guards - an introduction to patterns, guards, and extensions
- Syntax reference - the language syntax reference
- Typespecs- types and function specifications, including list of types
- Unicode syntax - outlines Elixir support for Unicode
- Writing documentation - guidelines for writing documentation in Elixir
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:
def drive(%User{age: age}) when age >= 16 do
...
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.
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
falsenornil - a value is falsy when it is either
falseornil
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.
Structural comparison
The functions in this module perform structural comparison. This allows different data types to be compared using comparison operators:
iex> 1 < :an_atom
true
This is possible so Elixir developers can create collections, such as dictionaries and ordered sets, that store a mixture of data types in them. To understand why this matters, let's discuss the two types of comparisons we find in software: structural and semantic.
Structural means we are comparing the underlying data structures and we often want those operations to be as fast as possible, because it is used to power several algorithms and data structures in the language. A semantic comparison worries about what each data type represents. For example, semantically speaking, it doesn't make sense to compare Time with Date.
One example that shows the differences between structural and semantic comparisons are strings: "alien" sorts less than "office" ("alien" < "office") but "álien" is greater than "office". This happens because < compares the underlying bytes that form the string. If you were doing alphabetical listing, you may want "álien" to also appear before "office".
This means comparisons in Elixir are structural, as it has the goal of comparing data types as efficiently as possible to create flexible and perform data structures. This distinction is specially important for functions that provide ordering, such as >/2, </2, >=/2, <=/2, min/2, and max/2. For example:
~D[2017-03-31] > ~D[2017-04-01]
will return true because structural comparison compares the :day field before :month or :year. In order to perform semantic comparisons, the relevant data-types provide a compare/2 function, such as Date.compare/2:
iex> Date.compare(~D[2017-03-31], ~D[2017-04-01])
:lt
Alternatively, you can use the functions in the Enum module to sort or compute a maximum/minimum:
iex> Enum.sort([~D[2017-03-31], ~D[2017-04-01]], Date)
[~D[2017-03-31], ~D[2017-04-01]]
iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]], Date)
~D[2017-04-01]
The second argument is precisely the module to be used for semantic comparison. Keeping this distinction is important, because if semantic comparison was used by default for implementing data structures and algorithms, they could become orders of magnitude slower!
Finally, note there is an overall structural sorting order, called "Term Ordering", defined below. This order is provided for reference purposes, it is not required by Elixir developers to know it by heart.
Term ordering
number < atom < reference < function < port < pid < tuple < map < list < bitstring
When comparing two numbers of different types (a number being either an integer or a float), a conversion to the type with greater precision will always occur, unless the comparison operator used is either ===/2 or !==. A float will be considered more precise than an integer, unless the float is greater/less than +/-9007199254740992.0 respectively, at which point all the significant figures of the float are to the left of the decimal point. This behavior exists so that the comparison of large numbers remains transitive.
The collection types are compared using the following rules:
- Tuples are compared by size, then element by element.
- Maps are compared by size, then by keys in ascending term order, then by values in key order. In the specific case of maps' key ordering, integers are always considered to be less than floats.
- Lists are compared element by element.
- Bitstrings are compared byte by byte, incomplete bytes are compared bit by bit.
- Atoms are compared using their string value, codepoint by codepoint.
Examples
We can check the truthiness of a value by using the !/1 function twice.
Truthy values:
iex> !!true
true
iex> !!5
true
iex> !![1,2]
true
iex> !!"foo"
true
Falsy values (of which there are exactly two):
iex> !!false
false
iex> !!nil
false
Inlining
Some of the functions described in this module are inlined by the Elixir compiler into their Erlang counterparts in the :erlang module. Those functions are called BIFs (built-in internal functions) in Erlang-land and they exhibit interesting properties, as some of them are allowed in guards and others are used for compiler optimizations.
Most of the inlined functions can be seen in effect when capturing the function:
iex> &Kernel.is_atom/1
&:erlang.is_atom/1
Those functions will be explicitly marked in their docs as "inlined by the compiler".
Guards
- left * right
-
Arithmetic multiplication operator.
- +value
-
Arithmetic positive unary operator.
- left + right
-
Arithmetic addition operator.
- -value
-
Arithmetic negative unary operator.
- left - right
-
Arithmetic subtraction operator.
- left / right
-
Arithmetic division operator.
- left != right
-
Not equal to operator.
- left !== right
-
Strictly not equal to operator.
- left < right
-
Less-than operator.
- left <= right
-
Less-than or equal to operator.
- left == right
-
Equal to operator. Returns
trueif the two terms are equal. - left === right
-
Strictly equal to operator.
- left > right
-
Greater-than operator.
- left >= right
-
Greater-than or equal to operator.
- abs(number)
-
Returns an integer or float which is the arithmetical absolute value of
number. - left and right
-
Strictly boolean "and" operator.
- binary_part(binary, start, length)
-
Extracts the part of the binary starting at
startwith lengthlength. Binaries are zero-indexed. - bit_size(bitstring)
-
Returns an integer which is the size in bits of
bitstring. - byte_size(bitstring)
-
Returns the number of bytes needed to contain
bitstring. - ceil(number)
-
Returns the smallest integer greater than or equal to
number. - div(dividend, divisor)
-
Performs an integer division.
- elem(tuple, index)
-
Gets the element at the zero-based
indexintuple. - floor(number)
-
Returns the largest integer smaller than or equal to
number. - hd(list)
-
Returns the head of a list. Raises
ArgumentErrorif the list is empty. - left in right
-
Membership operator.
- is_atom(term)
-
Returns
trueiftermis an atom; otherwise returnsfalse. - is_binary(term)
-
Returns
trueiftermis a binary; otherwise returnsfalse. - is_bitstring(term)
-
Returns
trueiftermis a bitstring (including a binary); otherwise returnsfalse. - is_boolean(term)
-
Returns
trueiftermis either the atomtrueor the atomfalse(i.e., a boolean); otherwise returnsfalse. - is_exception(term)
-
Returns true if
termis an exception; otherwise returnsfalse. - is_exception(term, name)
-
Returns true if
termis an exception ofname; otherwise returnsfalse. - is_float(term)
-
Returns
trueiftermis a floating-point number; otherwise returnsfalse. - is_function(term)
-
Returns
trueiftermis a function; otherwise returnsfalse. - is_function(term, arity)
-
Returns
trueiftermis a function that can be applied witharitynumber of arguments; otherwise returnsfalse. - is_integer(term)
-
Returns
trueiftermis an integer; otherwise returnsfalse. - is_list(term)
-
Returns
trueiftermis a list with zero or more elements; otherwise returnsfalse. - is_map(term)
-
Returns
trueiftermis a map; otherwise returnsfalse. - is_map_key(map, key)
-
Returns
trueifkeyis a key inmap; otherwise returnsfalse. - is_nil(term)
-
Returns
trueiftermisnil,falseotherwise. - is_number(term)
-
Returns
trueiftermis either an integer or a floating-point number; otherwise returnsfalse. - is_pid(term)
-
Returns
trueiftermis a PID (process identifier); otherwise returnsfalse. - is_port(term)
-
Returns
trueiftermis a port identifier; otherwise returnsfalse. - is_reference(term)
-
Returns
trueiftermis a reference; otherwise returnsfalse. - is_struct(term)
-
Returns true if
termis a struct; otherwise returnsfalse. - is_struct(term, name)
-
Returns true if
termis a struct ofname; otherwise returnsfalse. - is_tuple(term)
-
Returns
trueiftermis a tuple; otherwise returnsfalse. - length(list)
-
Returns the length of
list. - map_size(map)
-
Returns the size of a map.
- node()
-
Returns an atom representing the name of the local node. If the node is not alive,
:nonode@nohostis 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@nohostis returned. - not value
-
Strictly boolean "not" operator.
- left or right
-
Strictly boolean "or" operator.
- rem(dividend, divisor)
-
Computes the remainder of an integer division.
- round(number)
-
Rounds a number to the nearest integer.
- self()
-
Returns the PID (process identifier) of the calling process.
- tl(list)
-
Returns the tail of a list. Raises
ArgumentErrorif the list is empty. - trunc(number)
-
Returns the integer part of
number. - tuple_size(tuple)
-
Returns the size of a tuple.
Functions
- left && right
-
Boolean "and" operator.
- base ** exponent
-
Power operator.
- left ++ right
-
List concatenation operator. Concatenates a proper list and a term, returning a list.
- left -- right
-
List subtraction operator. Removes the first occurrence of an element on the left list for each element on the right.
- ..
-
Creates the full-slice range
0..-1//1. - first..last
-
Creates a range from
firsttolast. - first..last//step
-
Creates a range from
firsttolastwithstep. - !value
-
Boolean "not" operator.
- left <> right
-
Binary concatenation operator. Concatenates two binaries.
- left =~ right
-
Text-based match operator. Matches the term on the
leftagainst the regular expression or string on theright. - @expr
-
Module attribute unary operator.
- alias!(alias)
-
When used inside quoting, marks that the given alias should not be hygienized. This means the alias will be expanded when the macro is expanded.
- apply(fun, args)
-
Invokes the given anonymous function
funwith the list of argumentsargs. - apply(module, function_name, args)
-
Invokes the given function from
modulewith the list of argumentsargs. - binary_slice(binary, range)
-
Returns a binary from the offset given by the start of the range to the offset given by the end of the range.
- binary_slice(binary, start, size)
-
Returns a binary starting at the offset
startand of the givensize. - binding(context \\ nil)
-
Returns the binding for the given context as a keyword list.
- dbg(code \\ quote do binding() end, options \\ [])
-
Debugs the given
code. - def(call, expr \\ nil)
-
Defines a public function with the given name and body.
- defdelegate(funs, opts)
-
Defines a function that delegates to another module.
- defexception(fields)
-
Defines an exception.
- defguard(guard)
-
Generates a macro suitable for use in guard expressions.
- defguardp(guard)
-
Generates a private macro suitable for use in guard expressions.
- defimpl(name, opts, do_block \\ [])
-
Defines an implementation for the given protocol.
- defmacro(call, expr \\ nil)
-
Defines a public macro with the given name and body.
- defmacrop(call, expr \\ nil)
-
Defines a private macro with the given name and body.
- defmodule(alias, do_block)
-
Defines a module given by name with the given contents.
- defoverridable(keywords_or_behaviour)
-
Makes the given definitions in the current module overridable.
- defp(call, expr \\ nil)
-
Defines a private function with the given name and body.
- defprotocol(name, do_block)
-
Defines a protocol.
- defstruct(fields)
-
Defines a struct.
- destructure(left, right)
-
Destructures two lists, assigning each term in the right one to the matching term in the left one.
- exit(reason)
-
Stops the execution of the calling process with the given reason.
- function_exported?(module, function, arity)
-
Returns
trueifmoduleis loaded and contains a publicfunctionwith the givenarity, otherwisefalse. - get_and_update_in(path, fun)
-
Gets a value and updates a nested data structure via the given
path. - get_and_update_in(data, keys, fun)
-
Gets a value and updates a nested structure.
- get_in(data, keys)
-
Gets a value from a nested structure.
- if(condition, clauses)
-
Provides an
if/2macro. - inspect(term, opts \\ [])
-
Inspects the given argument according to the
Inspectprotocol. The second argument is a keyword list with options to control inspection. - macro_exported?(module, macro, arity)
-
Returns
trueifmoduleis loaded and contains a publicmacrowith the givenarity, otherwisefalse. - make_ref()
-
Returns an almost unique reference.
- match?(pattern, expr)
-
A convenience macro that checks if the right side (an expression) matches the left side (a pattern).
- max(first, second)
-
Returns the biggest of the two given terms according to their structural comparison.
- min(first, second)
-
Returns the smallest of the two given terms according to their structural comparison.
- pop_in(path)
-
Pops a key from the nested structure via the given
path. - pop_in(data, keys)
-
Pops a key from the given nested structure.
- put_elem(tuple, index, value)
-
Puts
valueat the given zero-basedindexintuple. - put_in(path, value)
-
Puts a value in a nested structure via the given
path. - put_in(data, keys, value)
-
Puts a value in a nested structure.
- raise(message)
-
Raises an exception.
- raise(exception, attributes)
-
Raises an exception.
- reraise(message, stacktrace)
-
Raises an exception preserving a previous stacktrace.
- reraise(exception, attributes, stacktrace)
-
Raises an exception preserving a previous stacktrace.
- send(dest, message)
-
Sends a message to the given
destand returns the message. - sigil_C(term, modifiers)
-
Handles the sigil
~Cfor charlists. - sigil_c(term, modifiers)
-
Handles the sigil
~cfor charlists. - sigil_D(date_string, modifiers)
-
Handles the sigil
~Dfor dates. - sigil_N(naive_datetime_string, modifiers)
-
Handles the sigil
~Nfor naive date times. - sigil_R(term, modifiers)
-
Handles the sigil
~Rfor regular expressions. - sigil_r(term, modifiers)
-
Handles the sigil
~rfor regular expressions. - sigil_S(term, modifiers)
-
Handles the sigil
~Sfor strings. - sigil_s(term, modifiers)
-
Handles the sigil
~sfor strings. - sigil_T(time_string, modifiers)
-
Handles the sigil
~Tfor times. - sigil_U(datetime_string, modifiers)
-
Handles the sigil
~Uto create a UTCDateTime. - sigil_W(term, modifiers)
-
Handles the sigil
~Wfor list of words. - sigil_w(term, modifiers)
-
Handles the sigil
~wfor list of words. - spawn(fun)
-
Spawns the given function and returns its PID.
- spawn(module, fun, args)
-
Spawns the given function
funfrom the givenmodulepassing it the givenargsand 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 function
funfrom the givenmodulepassing it the givenargs, links it to the current process, and returns its PID. - spawn_monitor(fun)
-
Spawns the given function, monitors it and returns its PID and monitoring reference.
- spawn_monitor(module, fun, args)
-
Spawns the given module and function passing the given args, monitors it and returns its PID and monitoring reference.
- struct(struct, fields \\ [])
-
Creates and updates a struct.
- struct!(struct, fields \\ [])
-
Similar to
struct/2but checks for key validity. - tap(value, fun)
-
Pipes the first argument,
value, into the second argument, a functionfun, and returnsvalueitself. - then(value, fun)
-
Pipes the first argument,
value, into the second argument, a functionfun, and returns the result of callingfun. - throw(term)
-
A non-local return from a function.