elixir / 1.15 / kernel.html

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, and nil are atoms)
  • Float - numbers with floating point precision
  • Function - a reference to code chunk, created with the fn/1 special form
  • Integer - whole numbers (not fractions)
  • List - collections of a variable number of elements (linked lists)
  • Map - collections of key-value pairs
  • Process - light-weight threads of execution
  • Port - mechanisms to interact with the external world
  • Tuple - collections of a fixed number of elements

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 :binary module
  • 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-day structs in a given calendar
  • DateTime - date and time with time zone in a given calendar
  • Exception - data raised from errors and unexpected scenarios
  • MapSet - unordered collections of unique elements
  • NaiveDateTime - date and time without time zone in a given calendar
  • Keyword - lists of two-element tuples, often representing optional values
  • Range - inclusive ranges between two integers
  • Regex - regular expressions
  • String - UTF-8 encoded binaries representing characters
  • Time - hour:minute:second structs in a given calendar
  • URI - representation of URIs that identify resources
  • Version - representation of versions and requirements

System modules

Modules that interface with the underlying system, such as:

  • IO - handles input and output
  • File - interacts with the underlying file system
  • Path - manipulates file system paths
  • System - 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 type
  • Enumerable - handles collections in Elixir. The Enum module provides eager functions for working with collections, the Stream module provides lazy functions
  • Inspect - converts data types into their programming language representation
  • List.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 state
  • Application - functions for starting, stopping and configuring applications
  • GenServer - a generic client-server API
  • Registry - a key-value process-based storage
  • Supervisor - a process that is responsible for starting, supervising and shutting down other processes
  • Task - a process that performs computations
  • Task.Supervisor - a supervisor for managing tasks exclusively

Supporting documents

Elixir documentation also includes supporting documents under the "Pages" section. Those are:

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 false nor nil
  • a value is falsy when it is either false or nil

Elixir has functions, like and/2, that only work with booleans, but also functions that work with these truthy/falsy values, like &&/2 and !/1.

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 true if 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 start with length length. 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 index in tuple.

floor(number)

Returns the largest integer smaller than or equal to number.

hd(list)

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

left in right

Membership operator.

is_atom(term)

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

is_binary(term)

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

is_bitstring(term)

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

is_boolean(term)

Returns true if term is either the atom true or the atom false (i.e., a boolean); otherwise returns false.

is_exception(term)

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

is_exception(term, name)

Returns true if term is an exception of name; otherwise returns false.

is_float(term)

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

is_function(term)

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

is_function(term, arity)

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

is_integer(term)

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

is_list(term)

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

is_map(term)

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

is_map_key(map, key)

Returns true if key is a key in map; otherwise returns false.

is_nil(term)

Returns true if term is nil, false otherwise.

is_number(term)

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

is_pid(term)

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

is_port(term)

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

is_reference(term)

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

is_struct(term)

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

is_struct(term, name)

Returns true if term is a struct of name; otherwise returns false.

is_tuple(term)

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

length(list)

Returns the length of list.

map_size(map)

Returns the size of a map.

node()

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

node(arg)

Returns the node where the given argument is located. The argument can be a PID, a reference, or a port. If the local node is not alive, :nonode@nohost is returned.

not value

Strictly boolean "not" operator.

left or right

Strictly boolean "or" operator.

rem(dividend, divisor)

Computes the remainder of an integer division.

round(number)

Rounds a number to the nearest integer.

self()

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

tl(list)

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

trunc(number)

Returns the integer part of number.

tuple_size(tuple)

Returns the size of a tuple.

Functions

left && right

Boolean "and" operator.

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 first to last.

first..last//step

Creates a range from first to last with step.

!value

Boolean "not" operator.

left <> right

Binary concatenation operator. Concatenates two binaries.

left =~ right

Text-based match operator. Matches the term on the left against the regular expression or string on the right.

@expr

Module attribute unary operator.

alias!(alias)

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

apply(fun, args)

Invokes the given anonymous function fun with the list of arguments args.

apply(module, function_name, args)

Invokes the given function from module with the list of arguments args.

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 start and of the given size.

binding(context \\ nil)

Returns the binding for the given context as a keyword list.

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 true if module is loaded and contains a public function with the given arity, otherwise false.

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/2 macro.

inspect(term, opts \\ [])

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

macro_exported?(module, macro, arity)

Returns true if 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 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 value at the given zero-based index in tuple.

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 dest and returns the message.

sigil_C(term, modifiers)

Handles the sigil ~C for charlists.

sigil_c(term, modifiers)

Handles the sigil ~c for charlists.

sigil_D(date_string, modifiers)

Handles the sigil ~D for dates.

sigil_N(naive_datetime_string, modifiers)

Handles the sigil ~N for naive date times.

sigil_R(term, modifiers)

Handles the sigil ~R for regular expressions.

sigil_r(term, modifiers)

Handles the sigil ~r for regular expressions.

sigil_S(term, modifiers)

Handles the sigil ~S for strings.

sigil_s(term, modifiers)

Handles the sigil ~s for strings.

sigil_T(time_string, modifiers)

Handles the sigil ~T for times.

sigil_U(datetime_string, modifiers)

Handles the sigil ~U to create a UTC DateTime.

sigil_W(term, modifiers)

Handles the sigil ~W for list of words.

sigil_w(term, modifiers)

Handles the sigil ~w for list of words.

spawn(fun)

Spawns the given function and returns its PID.

spawn(module, fun, args)

Spawns the given function fun from the given module passing it 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 function fun from the given module passing it the given args, 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/2 but checks for key validity.

tap(value, fun)

Pipes the first argument, value, into the second argument, a function fun, and returns value itself.

then(value, fun)

Pipes the first argument, value, into the second argument, a function fun, and returns the result of calling fun.

throw(term)

A non-local return from a function.