W3cubDocs

/Elixir 1.5

Enum

Provides a set of algorithms that enumerate over enumerables according to the Enumerable protocol.

iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)
[2, 4, 6]

Some particular types, like maps, yield a specific format on enumeration. For example, the argument is always a {key, value} tuple for maps:

iex> map = %{a: 1, b: 2}
iex> Enum.map(map, fn {k, v} -> {k, v * 2} end)
[a: 2, b: 4]

Note that the functions in the Enum module are eager: they always start the enumeration of the given enumerable. The Stream module allows lazy enumeration of enumerables and provides infinite streams.

Since the majority of the functions in Enum enumerate the whole enumerable and return a list as result, infinite streams need to be carefully used with such functions, as they can potentially run forever. For example:

Enum.each Stream.cycle([1, 2, 3]), &IO.puts(&1)

Summary

Types

acc()
default()
element()
index()
t()

Functions

all?(enumerable, fun \\ fn x -> x end)

Returns true if the given fun evaluates to true on all of the items in the enumerable

any?(enumerable, fun \\ fn x -> x end)

Returns true if the given fun evaluates to true on any of the items in the enumerable

at(enumerable, index, default \\ nil)

Finds the element at the given index (zero-based)

chunk_by(enumerable, fun)

Splits enumerable on every element for which fun returns a new value

chunk_every(enumerable, count)

Shortcut to chunk_every(enumerable, count, count)

chunk_every(enumerable, count, step, leftover \\ [])

Returns list of lists containing count items each, where each new chunk starts step elements into the enumerable

chunk_while(enum, acc, chunk_fun, after_fun)

Chunks the enum with fine grained control when every chunk is emitted

concat(enumerables)

Given an enumerable of enumerables, concatenates the enumerables into a single list

concat(left, right)

Concatenates the enumerable on the right with the enumerable on the left

count(enumerable)

Returns the size of the enumerable

count(enumerable, fun)

Returns the count of items in the enumerable for which fun returns a truthy value

dedup(enumerable)

Enumerates the enumerable, returning a list where all consecutive duplicated elements are collapsed to a single element

dedup_by(enumerable, fun)

Enumerates the enumerable, returning a list where all consecutive duplicated elements are collapsed to a single element

drop(enumerable, amount)

Drops the amount of items from the enumerable

drop_every(enumerable, nth)

Returns a list of every nth item in the enumerable dropped, starting with the first element

drop_while(enumerable, fun)

Drops items at the beginning of the enumerable while fun returns a truthy value

each(enumerable, fun)

Invokes the given fun for each item in the enumerable

empty?(enumerable)

Determines if the enumerable is empty

fetch(enumerable, index)

Finds the element at the given index (zero-based)

fetch!(enumerable, index)

Finds the element at the given index (zero-based)

filter(enumerable, fun)

Filters the enumerable, i.e. returns only those elements for which fun returns a truthy value

find(enumerable, default \\ nil, fun)

Returns the first item for which fun returns a truthy value. If no such item is found, returns default

find_index(enumerable, fun)

Similar to find/3, but returns the index (zero-based) of the element instead of the element itself

find_value(enumerable, default \\ nil, fun)

Similar to find/3, but returns the value of the function invocation instead of the element itself

flat_map(enumerable, fun)

Maps the given fun over enumerable and flattens the result

flat_map_reduce(enumerable, acc, fun)

Maps and reduces an enumerable, flattening the given results (only one level deep)

group_by(enumerable, key_fun, value_fun \\ fn x -> x end)

Splits the enumerable into groups based on key_fun

intersperse(enumerable, element)

Intersperses element between each element of the enumeration

into(enumerable, collectable)

Inserts the given enumerable into a collectable

into(enumerable, collectable, transform)

Inserts the given enumerable into a collectable according to the transformation function

join(enumerable, joiner \\ "")

Joins the given enumerable into a binary using joiner as a separator

map(enumerable, fun)

Returns a list where each item is the result of invoking fun on each corresponding item of enumerable

map_every(enumerable, nth, fun)

Returns a list of results of invoking fun on every nth item of enumerable, starting with the first element

map_join(enumerable, joiner \\ "", mapper)

Maps and joins the given enumerable in one pass

map_reduce(enumerable, acc, fun)

Invokes the given function to each item in the enumerable to reduce it to a single element, while keeping an accumulator

max(enumerable, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

Returns the maximal element in the enumerable according to Erlang’s term ordering

max_by(enumerable, fun, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

Returns the maximal element in the enumerable as calculated by the given function

member?(enumerable, element)

Checks if element exists within the enumerable

min(enumerable, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

Returns the minimal element in the enumerable according to Erlang’s term ordering

min_by(enumerable, fun, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

Returns the minimal element in the enumerable as calculated by the given function

min_max(enumerable, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

Returns a tuple with the minimal and the maximal elements in the enumerable according to Erlang’s term ordering

min_max_by(enumerable, fun, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

Returns a tuple with the minimal and the maximal elements in the enumerable as calculated by the given function

random(enumerable)

Returns a random element of an enumerable

reduce(enumerable, fun)

Invokes fun for each element in the enumerable with the accumulator

reduce(enumerable, acc, fun)

Invokes fun for each element in the enumerable with the accumulator

reduce_while(enumerable, acc, fun)

Reduces the enumerable until fun returns {:halt, term}

reject(enumerable, fun)

Returns elements of enumerable for which the function fun returns false or nil

reverse(enumerable)

Returns a list of elements in enumerable in reverse order

reverse(enumerable, tail)

Reverses the elements in enumerable, appends the tail, and returns it as a list

reverse_slice(enumerable, start, count)

Reverses the enumerable in the range from initial position start through count elements

scan(enumerable, fun)

Applies the given function to each element in the enumerable, storing the result in a list and passing it as the accumulator for the next computation. Uses the first element in the enumerable as the starting value

scan(enumerable, acc, fun)

Applies the given function to each element in the enumerable, storing the result in a list and passing it as the accumulator for the next computation. Uses the given acc as the starting value

shuffle(enumerable)

Returns a list with the elements of enumerable shuffled

slice(enumerable, range)

Returns a subset list of the given enumerable, from range.first to range.last positions

slice(enumerable, start, amount)

Returns a subset list of the given enumerable, from start position with amount of elements if available

sort(enumerable)

Sorts the enumerable according to Erlang’s term ordering

sort(enumerable, fun)

Sorts the enumerable by the given function

sort_by(enumerable, mapper, sorter \\ &<=/2)

Sorts the mapped results of the enumerable according to the provided sorter function

split(enumerable, count)

Splits the enumerable into two enumerables, leaving count elements in the first one

split_while(enumerable, fun)

Splits enumerable in two at the position of the element for which fun returns false for the first time

split_with(enumerable, fun)

Splits the enumerable in two lists according to the given function fun

sum(enumerable)

Returns the sum of all elements

take(enumerable, count)

Takes the first count items from the enumerable

take_every(enumerable, nth)

Returns a list of every nth item in the enumerable, starting with the first element

take_random(enumerable, count)

Takes count random items from enumerable

take_while(enumerable, fun)

Takes the items from the beginning of the enumerable while fun returns a truthy value

to_list(enumerable)

Converts enumerable to a list

uniq(enumerable)

Enumerates the enumerable, removing all duplicated elements

uniq_by(enumerable, fun)

Enumerates the enumerable, by removing the elements for which function fun returned duplicate items

unzip(enumerable)

Opposite of Enum.zip/2; extracts a two-element tuples from the enumerable and groups them together

with_index(enumerable, offset \\ 0)

Returns the enumerable with each element wrapped in a tuple alongside its index

zip(enumerables)

Zips corresponding elements from a collection of enumerables into one list of tuples

zip(enumerable1, enumerable2)

Zips corresponding elements from two enumerables into one list of tuples

Types

acc()

acc() :: any

default()

default() :: any

element()

element() :: any

index()

index() :: integer

t()

t() :: Enumerable.t

Functions

all?(enumerable, fun \\ fn x -> x end)

all?(t, (element -> as_boolean(term))) :: boolean

Returns true if the given fun evaluates to true on all of the items in the enumerable.

It stops the iteration at the first invocation that returns false or nil.

Examples

iex> Enum.all?([2, 4, 6], fn(x) -> rem(x, 2) == 0 end)
true

iex> Enum.all?([2, 3, 4], fn(x) -> rem(x, 2) == 0 end)
false

If no function is given, it defaults to checking if all items in the enumerable are truthy values.

iex> Enum.all?([1, 2, 3])
true

iex> Enum.all?([1, nil, 3])
false

any?(enumerable, fun \\ fn x -> x end)

any?(t, (element -> as_boolean(term))) :: boolean

Returns true if the given fun evaluates to true on any of the items in the enumerable.

It stops the iteration at the first invocation that returns a truthy value (not false or nil).

Examples

iex> Enum.any?([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)
false

iex> Enum.any?([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)
true

If no function is given, it defaults to checking if at least one item in the enumerable is a truthy value.

iex> Enum.any?([false, false, false])
false

iex> Enum.any?([false, true, false])
true

at(enumerable, index, default \\ nil)

at(t, index, default) :: element | default

Finds the element at the given index (zero-based).

Returns default if index is out of bounds.

A negative index can be passed, which means the enumerable is enumerated once and the index is counted from the end (e.g. -1 finds the last element).

Note this operation takes linear time. In order to access the element at index index, it will need to traverse index previous elements.

Examples

iex> Enum.at([2, 4, 6], 0)
2

iex> Enum.at([2, 4, 6], 2)
6

iex> Enum.at([2, 4, 6], 4)
nil

iex> Enum.at([2, 4, 6], 4, :none)
:none

chunk_by(enumerable, fun)

chunk_by(t, (element -> any)) :: [list]

Splits enumerable on every element for which fun returns a new value.

Returns a list of lists.

Examples

iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))
[[1], [2, 2], [3], [4, 4, 6], [7, 7]]

chunk_every(enumerable, count)

chunk_every(t, pos_integer) :: [list]

Shortcut to chunk_every(enumerable, count, count).

chunk_every(enumerable, count, step, leftover \\ [])

chunk_every(t, pos_integer, pos_integer, t | :discard) :: [list]

Returns list of lists containing count items each, where each new chunk starts step elements into the enumerable.

step is optional and, if not passed, defaults to count, i.e. chunks do not overlap.

If the last chunk does not have count elements to fill the chunk, elements are taken from leftover to fill in the chunk. If leftover does not have enough elements to fill the chunk, then a partial chunk is returned with less than count elements.

If :discard is given in leftover, the last chunk is discarded unless it has exactly count elements.

Examples

iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 2)
[[1, 2], [3, 4], [5, 6]]

iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, :discard)
[[1, 2, 3], [3, 4, 5]]

iex> Enum.chunk_every([1, 2, 3, 4, 5, 6], 3, 2, [7])
[[1, 2, 3], [3, 4, 5], [5, 6, 7]]

iex> Enum.chunk_every([1, 2, 3, 4], 3, 3, [])
[[1, 2, 3], [4]]

iex> Enum.chunk_every([1, 2, 3, 4], 10)
[[1, 2, 3, 4]]

chunk_while(enum, acc, chunk_fun, after_fun)

chunk_while(t, acc, (element, acc -> {:cont, chunk, acc} | {:cont, acc} | {:halt, acc}), (acc -> {:cont, chunk, acc} | {:cont, acc})) :: Enumerable.t when chunk: any

Chunks the enum with fine grained control when every chunk is emitted.

chunk_fun receives the current element and the accumulator and must return {:cont, element, acc} to emit the given chunk and continue with accumulator or {:cont, acc} to not emit any chunk and continue with the return accumulator.

after_fun is invoked when iteration is done and must also return {:cont, element, acc} or {:cont, acc}.

Returns a list of lists.

Examples

iex> chunk_fun = fn i, acc ->
...>   if rem(i, 2) == 0 do
...>     {:cont, Enum.reverse([i | acc]), []}
...>   else
...>     {:cont, [i | acc]}
...>   end
...> end
iex> after_fun = fn
...>   [] -> {:cont, []}
...>   acc -> {:cont, Enum.reverse(acc), []}
...> end
iex> Enum.chunk_while(1..10, [], chunk_fun, after_fun)
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

concat(enumerables)

concat(t) :: t

Given an enumerable of enumerables, concatenates the enumerables into a single list.

Examples

iex> Enum.concat([1..3, 4..6, 7..9])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

iex> Enum.concat([[1, [2], 3], [4], [5, 6]])
[1, [2], 3, 4, 5, 6]

concat(left, right)

concat(t, t) :: t

Concatenates the enumerable on the right with the enumerable on the left.

This function produces the same result as the Kernel.++/2 operator for lists.

Examples

iex> Enum.concat(1..3, 4..6)
[1, 2, 3, 4, 5, 6]

iex> Enum.concat([1, 2, 3], [4, 5, 6])
[1, 2, 3, 4, 5, 6]

count(enumerable)

count(t) :: non_neg_integer

Returns the size of the enumerable.

Examples

iex> Enum.count([1, 2, 3])
3

count(enumerable, fun)

count(t, (element -> as_boolean(term))) :: non_neg_integer

Returns the count of items in the enumerable for which fun returns a truthy value.

Examples

iex> Enum.count([1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end)
2

dedup(enumerable)

dedup(t) :: list

Enumerates the enumerable, returning a list where all consecutive duplicated elements are collapsed to a single element.

Elements are compared using ===.

If you want to remove all duplicated elements, regardless of order, see uniq/1.

Examples

iex> Enum.dedup([1, 2, 3, 3, 2, 1])
[1, 2, 3, 2, 1]

iex> Enum.dedup([1, 1, 2, 2.0, :three, :"three"])
[1, 2, 2.0, :three]

dedup_by(enumerable, fun)

dedup_by(t, (element -> term)) :: list

Enumerates the enumerable, returning a list where all consecutive duplicated elements are collapsed to a single element.

The function fun maps every element to a term which is used to determine if two elements are duplicates.

Examples

iex> Enum.dedup_by([{1, :a}, {2, :b}, {2, :c}, {1, :a}], fn {x, _} -> x end)
[{1, :a}, {2, :b}, {1, :a}]

iex> Enum.dedup_by([5, 1, 2, 3, 2, 1], fn x -> x > 2 end)
[5, 1, 3, 2]

drop(enumerable, amount)

drop(t, integer) :: list

Drops the amount of items from the enumerable.

If a negative amount is given, the amount of last values will be dropped.

The enumerable is enumerated once to retrieve the proper index and the remaining calculation is performed from the end.

Examples

iex> Enum.drop([1, 2, 3], 2)
[3]

iex> Enum.drop([1, 2, 3], 10)
[]

iex> Enum.drop([1, 2, 3], 0)
[1, 2, 3]

iex> Enum.drop([1, 2, 3], -1)
[1, 2]

drop_every(enumerable, nth)

drop_every(t, non_neg_integer) :: list

Returns a list of every nth item in the enumerable dropped, starting with the first element.

The first item is always dropped, unless nth is 0.

The second argument specifying every nth item must be a non-negative integer.

Examples

iex> Enum.drop_every(1..10, 2)
[2, 4, 6, 8, 10]

iex> Enum.drop_every(1..10, 0)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

iex> Enum.drop_every([1, 2, 3], 1)
[]

drop_while(enumerable, fun)

drop_while(t, (element -> as_boolean(term))) :: list

Drops items at the beginning of the enumerable while fun returns a truthy value.

Examples

iex> Enum.drop_while([1, 2, 3, 2, 1], fn(x) -> x < 3 end)
[3, 2, 1]

each(enumerable, fun)

each(t, (element -> any)) :: :ok

Invokes the given fun for each item in the enumerable.

Returns :ok.

Examples

Enum.each(["some", "example"], fn(x) -> IO.puts x end)
"some"
"example"
#=> :ok

empty?(enumerable)

empty?(t) :: boolean

Determines if the enumerable is empty.

Returns true if enumerable is empty, otherwise false.

Examples

iex> Enum.empty?([])
true

iex> Enum.empty?([1, 2, 3])
false

fetch(enumerable, index)

fetch(t, index) :: {:ok, element} | :error

Finds the element at the given index (zero-based).

Returns {:ok, element} if found, otherwise :error.

A negative index can be passed, which means the enumerable is enumerated once and the index is counted from the end (e.g. -1 fetches the last element).

Note this operation takes linear time. In order to access the element at index index, it will need to traverse index previous elements.

Examples

iex> Enum.fetch([2, 4, 6], 0)
{:ok, 2}

iex> Enum.fetch([2, 4, 6], -3)
{:ok, 2}

iex> Enum.fetch([2, 4, 6], 2)
{:ok, 6}

iex> Enum.fetch([2, 4, 6], 4)
:error

fetch!(enumerable, index)

fetch!(t, index) :: element | no_return

Finds the element at the given index (zero-based).

Raises OutOfBoundsError if the given index is outside the range of the enumerable.

Note this operation takes linear time. In order to access the element at index index, it will need to traverse index previous elements.

Examples

iex> Enum.fetch!([2, 4, 6], 0)
2

iex> Enum.fetch!([2, 4, 6], 2)
6

iex> Enum.fetch!([2, 4, 6], 4)
** (Enum.OutOfBoundsError) out of bounds error

filter(enumerable, fun)

filter(t, (element -> as_boolean(term))) :: list

Filters the enumerable, i.e. returns only those elements for which fun returns a truthy value.

See also reject/2.

Examples

iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)
[2]

find(enumerable, default \\ nil, fun)

find(t, default, (element -> any)) :: element | default

Returns the first item for which fun returns a truthy value. If no such item is found, returns default.

Examples

iex> Enum.find([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)
nil

iex> Enum.find([2, 4, 6], 0, fn(x) -> rem(x, 2) == 1 end)
0

iex> Enum.find([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)
3

find_index(enumerable, fun)

find_index(t, (element -> any)) :: non_neg_integer | nil

Similar to find/3, but returns the index (zero-based) of the element instead of the element itself.

Examples

iex> Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)
nil

iex> Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)
1

find_value(enumerable, default \\ nil, fun)

find_value(t, any, (element -> any)) :: any | nil

Similar to find/3, but returns the value of the function invocation instead of the element itself.

Examples

iex> Enum.find_value([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)
nil

iex> Enum.find_value([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)
true

iex> Enum.find_value([1, 2, 3], "no bools!", &is_boolean/1)
"no bools!"

flat_map(enumerable, fun)

flat_map(t, (element -> t)) :: list

Maps the given fun over enumerable and flattens the result.

This function returns a new enumerable built by appending the result of invoking fun on each element of enumerable together; conceptually, this is similar to a combination of map/2 and concat/1.

Examples

iex> Enum.flat_map([:a, :b, :c], fn(x) -> [x, x] end)
[:a, :a, :b, :b, :c, :c]

iex> Enum.flat_map([{1, 3}, {4, 6}], fn({x, y}) -> x..y end)
[1, 2, 3, 4, 5, 6]

iex> Enum.flat_map([:a, :b, :c], fn(x) -> [[x]] end)
[[:a], [:b], [:c]]

flat_map_reduce(enumerable, acc, fun)

flat_map_reduce(t, acc, fun) :: {[any], any} when fun: (element, acc -> {t, acc} | {:halt, acc}), acc: any

Maps and reduces an enumerable, flattening the given results (only one level deep).

It expects an accumulator and a function that receives each enumerable item, and must return a tuple containing a new enumerable (often a list) with the new accumulator or a tuple with :halt as first element and the accumulator as second.

Examples

iex> enum = 1..100
iex> n = 3
iex> Enum.flat_map_reduce(enum, 0, fn i, acc ->
...>   if acc < n, do: {[i], acc + 1}, else: {:halt, acc}
...> end)
{[1, 2, 3], 3}

iex> Enum.flat_map_reduce(1..5, 0, fn(i, acc) -> {[[i]], acc + i} end)
{[[1], [2], [3], [4], [5]], 15}

group_by(enumerable, key_fun, value_fun \\ fn x -> x end)

group_by(t, (element -> any), (element -> any)) :: map

Splits the enumerable into groups based on key_fun.

The result is a map where each key is given by key_fun and each value is a list of elements given by value_fun. Ordering is preserved.

Examples

iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1)
%{3 => ["ant", "cat"], 7 => ["buffalo"], 5 => ["dingo"]}

iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1, &String.first/1)
%{3 => ["a", "c"], 7 => ["b"], 5 => ["d"]}

intersperse(enumerable, element)

intersperse(t, element) :: list

Intersperses element between each element of the enumeration.

Complexity: O(n).

Examples

iex> Enum.intersperse([1, 2, 3], 0)
[1, 0, 2, 0, 3]

iex> Enum.intersperse([1], 0)
[1]

iex> Enum.intersperse([], 0)
[]

into(enumerable, collectable)

into(Enumerable.t, Collectable.t) :: Collectable.t

Inserts the given enumerable into a collectable.

Examples

iex> Enum.into([1, 2], [0])
[0, 1, 2]

iex> Enum.into([a: 1, b: 2], %{})
%{a: 1, b: 2}

iex> Enum.into(%{a: 1}, %{b: 2})
%{a: 1, b: 2}

iex> Enum.into([a: 1, a: 2], %{})
%{a: 2}

into(enumerable, collectable, transform)

into(Enumerable.t, Collectable.t, (term -> term)) :: Collectable.t

Inserts the given enumerable into a collectable according to the transformation function.

Examples

iex> Enum.into([2, 3], [3], fn x -> x * 3 end)
[3, 6, 9]

iex> Enum.into(%{a: 1, b: 2}, %{c: 3}, fn {k, v} -> {k, v * 2} end)
%{a: 2, b: 4, c: 3}

join(enumerable, joiner \\ "")

join(t, String.t) :: String.t

Joins the given enumerable into a binary using joiner as a separator.

If joiner is not passed at all, it defaults to the empty binary.

All items in the enumerable must be convertible to a binary, otherwise an error is raised.

Examples

iex> Enum.join([1, 2, 3])
"123"

iex> Enum.join([1, 2, 3], " = ")
"1 = 2 = 3"

map(enumerable, fun)

map(t, (element -> any)) :: list

Returns a list where each item is the result of invoking fun on each corresponding item of enumerable.

For maps, the function expects a key-value tuple.

Examples

iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)
[2, 4, 6]

iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end)
[a: -1, b: -2]

map_every(enumerable, nth, fun)

map_every(t, non_neg_integer, (element -> any)) :: list

Returns a list of results of invoking fun on every nth item of enumerable, starting with the first element.

The first item is always passed to the given function, unless nth is 0.

The second argument specifying every nth item must be a non-negative integer.

If nth is 0, then enumerable is directly converted to a list, without fun being ever applied.

Examples

iex> Enum.map_every(1..10, 2, fn x -> x + 1000 end)
[1001, 2, 1003, 4, 1005, 6, 1007, 8, 1009, 10]

iex> Enum.map_every(1..10, 3, fn x -> x + 1000 end)
[1001, 2, 3, 1004, 5, 6, 1007, 8, 9, 1010]

iex> Enum.map_every(1..5, 0, fn x -> x + 1000 end)
[1, 2, 3, 4, 5]

iex> Enum.map_every([1, 2, 3], 1, fn x -> x + 1000 end)
[1001, 1002, 1003]

map_join(enumerable, joiner \\ "", mapper)

map_join(t, String.t, (element -> String.Chars.t)) :: String.t

Maps and joins the given enumerable in one pass.

joiner can be either a binary or a list and the result will be of the same type as joiner. If joiner is not passed at all, it defaults to an empty binary.

All items returned from invoking the mapper must be convertible to a binary, otherwise an error is raised.

Examples

iex> Enum.map_join([1, 2, 3], &(&1 * 2))
"246"

iex> Enum.map_join([1, 2, 3], " = ", &(&1 * 2))
"2 = 4 = 6"

map_reduce(enumerable, acc, fun)

map_reduce(t, any, (element, any -> {any, any})) :: {any, any}

Invokes the given function to each item in the enumerable to reduce it to a single element, while keeping an accumulator.

Returns a tuple where the first element is the mapped enumerable and the second one is the final accumulator.

The function, fun, receives two arguments: the first one is the element, and the second one is the accumulator. fun must return a tuple with two elements in the form of {result, accumulator}.

For maps, the first tuple element must be a {key, value} tuple.

Examples

iex> Enum.map_reduce([1, 2, 3], 0, fn(x, acc) -> {x * 2, x + acc} end)
{[2, 4, 6], 6}

max(enumerable, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

max(t, (() -> empty_result)) ::
  element |
  empty_result |
  no_return when empty_result: any

Returns the maximal element in the enumerable according to Erlang’s term ordering.

If multiple elements are considered maximal, the first one that was found is returned.

Calls the provided empty_fallback function and returns its value if enumerable is empty. The default empty_fallback raises Enum.EmptyError.

Examples

iex> Enum.max([1, 2, 3])
3

iex> Enum.max([], fn -> 0 end)
0

max_by(enumerable, fun, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

max_by(t, (element -> any), (() -> empty_result)) ::
  element |
  empty_result |
  no_return when empty_result: any

Returns the maximal element in the enumerable as calculated by the given function.

If multiple elements are considered maximal, the first one that was found is returned.

Calls the provided empty_fallback function and returns its value if enumerable is empty. The default empty_fallback raises Enum.EmptyError.

Examples

iex> Enum.max_by(["a", "aa", "aaa"], fn(x) -> String.length(x) end)
"aaa"

iex> Enum.max_by(["a", "aa", "aaa", "b", "bbb"], &String.length/1)
"aaa"

iex> Enum.max_by([], &String.length/1, fn -> nil end)
nil

member?(enumerable, element)

member?(t, element) :: boolean

Checks if element exists within the enumerable.

Membership is tested with the match (===) operator.

Examples

iex> Enum.member?(1..10, 5)
true
iex> Enum.member?(1..10, 5.0)
false

iex> Enum.member?([1.0, 2.0, 3.0], 2)
false
iex> Enum.member?([1.0, 2.0, 3.0], 2.000)
true

iex> Enum.member?([:a, :b, :c], :d)
false

min(enumerable, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

min(t, (() -> empty_result)) ::
  element |
  empty_result |
  no_return when empty_result: any

Returns the minimal element in the enumerable according to Erlang’s term ordering.

If multiple elements are considered minimal, the first one that was found is returned.

Calls the provided empty_fallback function and returns its value if enumerable is empty. The default empty_fallback raises Enum.EmptyError.

Examples

iex> Enum.min([1, 2, 3])
1

iex> Enum.min([], fn -> 0 end)
0

min_by(enumerable, fun, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

min_by(t, (element -> any), (() -> empty_result)) ::
  element |
  empty_result |
  no_return when empty_result: any

Returns the minimal element in the enumerable as calculated by the given function.

If multiple elements are considered minimal, the first one that was found is returned.

Calls the provided empty_fallback function and returns its value if enumerable is empty. The default empty_fallback raises Enum.EmptyError.

Examples

iex> Enum.min_by(["a", "aa", "aaa"], fn(x) -> String.length(x) end)
"a"

iex> Enum.min_by(["a", "aa", "aaa", "b", "bbb"], &String.length/1)
"a"

iex> Enum.min_by([], &String.length/1, fn -> nil end)
nil

min_max(enumerable, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

min_max(t, (() -> empty_result)) ::
  {element, element} |
  empty_result |
  no_return when empty_result: any

Returns a tuple with the minimal and the maximal elements in the enumerable according to Erlang’s term ordering.

If multiple elements are considered maximal or minimal, the first one that was found is returned.

Calls the provided empty_fallback function and returns its value if enumerable is empty. The default empty_fallback raises Enum.EmptyError.

Examples

iex> Enum.min_max([2, 3, 1])
{1, 3}

iex> Enum.min_max([], fn -> {nil, nil} end)
{nil, nil}

min_max_by(enumerable, fun, empty_fallback \\ fn -> raise(Enum.EmptyError) end)

min_max_by(t, (element -> any), (() -> empty_result)) ::
  {element, element} |
  empty_result |
  no_return when empty_result: any

Returns a tuple with the minimal and the maximal elements in the enumerable as calculated by the given function.

If multiple elements are considered maximal or minimal, the first one that was found is returned.

Calls the provided empty_fallback function and returns its value if enumerable is empty. The default empty_fallback raises Enum.EmptyError.

Examples

iex> Enum.min_max_by(["aaa", "bb", "c"], fn(x) -> String.length(x) end)
{"c", "aaa"}

iex> Enum.min_max_by(["aaa", "a", "bb", "c", "ccc"], &String.length/1)
{"a", "aaa"}

iex> Enum.min_max_by([], &String.length/1, fn -> {nil, nil} end)
{nil, nil}

random(enumerable)

random(t) :: element | no_return

Returns a random element of an enumerable.

Raises Enum.EmptyError if enumerable is empty.

This function uses Erlang’s :rand module to calculate the random value. Check its documentation for setting a different random algorithm or a different seed.

The implementation is based on the reservoir sampling algorithm. It assumes that the sample being returned can fit into memory; the input enumerable doesn’t have to, as it is traversed just once.

If a range is passed into the function, this function will pick a random value between the range limits, without traversing the whole range (thus executing in constant time and constant memory).

Examples

# Although not necessary, let's seed the random algorithm
iex> :rand.seed(:exsplus, {101, 102, 103})
iex> Enum.random([1, 2, 3])
2
iex> Enum.random([1, 2, 3])
1
iex> Enum.random(1..1_000)
776

reduce(enumerable, fun)

reduce(t, (element, any -> any)) :: any

Invokes fun for each element in the enumerable with the accumulator.

The first element of the enumerable is used as the initial value of the accumulator. Then the function is invoked with the next element and the accumulator. The result returned by the function is used as the accumulator for the next iteration, recursively. When the enumerable is done, the last accumulator is returned.

Since the first element of the enumerable is used as the initial value of the accumulator, fun will only be executed n - 1 times where n is the length of the enumerable. This function won’t call the specified function for enumerables that are one-element long.

If you wish to use another value for the accumulator, use Enumerable.reduce/3.

Examples

iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end)
24

reduce(enumerable, acc, fun)

reduce(t, any, (element, any -> any)) :: any

Invokes fun for each element in the enumerable with the accumulator.

The initial value of the accumulator is acc. The function is invoked for each element in the enumerable with the accumulator. The result returned by the function is used as the accumulator for the next iteration. The function returns the last accumulator.

Examples

iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end)
6

Reduce as a building block

Reduce (sometimes called fold) is a basic building block in functional programming. Almost all of the functions in the Enum module can be implemented on top of reduce. Those functions often rely on other operations, such as Enum.reverse/1, which are optimized by the runtime.

For example, we could implement map/2 in terms of reduce/3 as follows:

def my_map(enumerable, fun) do
  enumerable
  |> Enum.reduce(enumerable, [], fn(x, acc) -> [fun.(x) | acc] end)
  |> Enum.reverse
end

In the example above, Enum.reduce/3 accumulates the result of each call to fun into a list in reverse order, which is correctly ordered at the end by calling Enum.reverse/1.

Implementing functions like map/2, filter/2 and others are a good exercise for understanding the power behind Enum.reduce/3. When an operation cannot be expressed by any of the functions in the Enum module, developers will most likely resort to reduce/3.

reduce_while(enumerable, acc, fun)

reduce_while(t, any, (element, any -> {:cont, any} | {:halt, any})) :: any

Reduces the enumerable until fun returns {:halt, term}.

The return value for fun is expected to be

  • {:cont, acc} to continue the reduction with acc as the new accumulator or
  • {:halt, acc} to halt the reduction and return acc as the return value of this function

Examples

iex> Enum.reduce_while(1..100, 0, fn i, acc ->
...>   if i < 3, do: {:cont, acc + i}, else: {:halt, acc}
...> end)
3

reject(enumerable, fun)

reject(t, (element -> as_boolean(term))) :: list

Returns elements of enumerable for which the function fun returns false or nil.

See also filter/2.

Examples

iex> Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)
[1, 3]

reverse(enumerable)

reverse(t) :: list

Returns a list of elements in enumerable in reverse order.

Examples

iex> Enum.reverse([1, 2, 3])
[3, 2, 1]

reverse(enumerable, tail)

reverse(t, t) :: list

Reverses the elements in enumerable, appends the tail, and returns it as a list.

This is an optimization for Enum.concat(Enum.reverse(enumerable), tail).

Examples

iex> Enum.reverse([1, 2, 3], [4, 5, 6])
[3, 2, 1, 4, 5, 6]

reverse_slice(enumerable, start, count)

reverse_slice(t, non_neg_integer, non_neg_integer) :: list

Reverses the enumerable in the range from initial position start through count elements.

If count is greater than the size of the rest of the enumerable, then this function will reverse the rest of the enumerable.

Examples

iex> Enum.reverse_slice([1, 2, 3, 4, 5, 6], 2, 4)
[1, 2, 6, 5, 4, 3]

scan(enumerable, fun)

scan(t, (element, any -> any)) :: list

Applies the given function to each element in the enumerable, storing the result in a list and passing it as the accumulator for the next computation. Uses the first element in the enumerable as the starting value.

Examples

iex> Enum.scan(1..5, &(&1 + &2))
[1, 3, 6, 10, 15]

scan(enumerable, acc, fun)

scan(t, any, (element, any -> any)) :: list

Applies the given function to each element in the enumerable, storing the result in a list and passing it as the accumulator for the next computation. Uses the given acc as the starting value.

Examples

iex> Enum.scan(1..5, 0, &(&1 + &2))
[1, 3, 6, 10, 15]

shuffle(enumerable)

shuffle(t) :: list

Returns a list with the elements of enumerable shuffled.

This function uses Erlang’s :rand module to calculate the random value. Check its documentation for setting a different random algorithm or a different seed.

Examples

# Although not necessary, let's seed the random algorithm
iex> :rand.seed(:exsplus, {1, 2, 3})
iex> Enum.shuffle([1, 2, 3])
[2, 1, 3]
iex> Enum.shuffle([1, 2, 3])
[2, 3, 1]

slice(enumerable, range)

slice(t, Range.t) :: list

Returns a subset list of the given enumerable, from range.first to range.last positions.

Given enumerable, it drops elements until element position range.first, then takes elements until element position range.last (inclusive).

Positions are normalized, meaning that negative positions will be counted from the end (e.g. -1 means the last element of the enumerable). If range.last is out of bounds, then it is assigned as the position of the last element.

If the normalized range.first position is out of bounds of the given enumerable, or this one is greater than the normalized range.last position, then [] is returned.

Examples

iex> Enum.slice(1..100, 5..10)
[6, 7, 8, 9, 10, 11]

iex> Enum.slice(1..10, 5..20)
[6, 7, 8, 9, 10]

# last five elements (negative positions)
iex> Enum.slice(1..30, -5..-1)
[26, 27, 28, 29, 30]

# last five elements (mixed positive and negative positions)
iex> Enum.slice(1..30, 25..-1)
[26, 27, 28, 29, 30]

# out of bounds
iex> Enum.slice(1..10, 11..20)
[]

# range.first is greater than range.last
iex> Enum.slice(1..10, 6..5)
[]

slice(enumerable, start, amount)

slice(t, index, non_neg_integer) :: list

Returns a subset list of the given enumerable, from start position with amount of elements if available.

Given enumerable, it drops elements until element position start, then takes amount of elements until the end of the enumerable.

If start is out of bounds, it returns [].

If amount is greater than enumerable length, it returns as many elements as possible. If amount is zero, then [] is returned.

Examples

iex> Enum.slice(1..100, 5, 10)
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# amount to take is greater than the number of elements
iex> Enum.slice(1..10, 5, 100)
[6, 7, 8, 9, 10]

iex> Enum.slice(1..10, 5, 0)
[]

# out of bound start position
iex> Enum.slice(1..10, 10, 5)
[]

# out of bound start position (negative)
iex> Enum.slice(1..10, -11, 5)
[]

sort(enumerable)

sort(t) :: list

Sorts the enumerable according to Erlang’s term ordering.

Uses the merge sort algorithm.

Examples

iex> Enum.sort([3, 2, 1])
[1, 2, 3]

sort(enumerable, fun)

sort(t, (element, element -> boolean)) :: list

Sorts the enumerable by the given function.

This function uses the merge sort algorithm. The given function should compare two arguments, and return true if the first argument precedes the second one.

Examples

iex> Enum.sort([1, 2, 3], &(&1 >= &2))
[3, 2, 1]

The sorting algorithm will be stable as long as the given function returns true for values considered equal:

iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) <= byte_size(&2))
["of", "some", "kind", "monster"]

If the function does not return true for equal values, the sorting is not stable and the order of equal terms may be shuffled. For example:

iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) < byte_size(&2))
["of", "kind", "some", "monster"]

sort_by(enumerable, mapper, sorter \\ &<=/2)

sort_by(t, (element -> mapped_element), (mapped_element, mapped_element -> boolean)) :: list when mapped_element: element

Sorts the mapped results of the enumerable according to the provided sorter function.

This function maps each element of the enumerable using the provided mapper function. The enumerable is then sorted by the mapped elements using the sorter function, which defaults to Kernel.<=/2.

sort_by/3 differs from sort/2 in that it only calculates the comparison value for each element in the enumerable once instead of once for each element in each comparison. If the same function is being called on both elements, it’s also more compact to use sort_by/3.

Examples

Using the default sorter of <=/2:

iex> Enum.sort_by ["some", "kind", "of", "monster"], &byte_size/1
["of", "some", "kind", "monster"]

Using a custom sorter to override the order:

iex> Enum.sort_by ["some", "kind", "of", "monster"], &byte_size/1, &>=/2
["monster", "some", "kind", "of"]

split(enumerable, count)

split(t, integer) :: {list, list}

Splits the enumerable into two enumerables, leaving count elements in the first one.

If count is a negative number, it starts counting from the back to the beginning of the enumerable.

Be aware that a negative count implies the enumerable will be enumerated twice: once to calculate the position, and a second time to do the actual splitting.

Examples

iex> Enum.split([1, 2, 3], 2)
{[1, 2], [3]}

iex> Enum.split([1, 2, 3], 10)
{[1, 2, 3], []}

iex> Enum.split([1, 2, 3], 0)
{[], [1, 2, 3]}

iex> Enum.split([1, 2, 3], -1)
{[1, 2], [3]}

iex> Enum.split([1, 2, 3], -5)
{[], [1, 2, 3]}

split_while(enumerable, fun)

split_while(t, (element -> as_boolean(term))) :: {list, list}

Splits enumerable in two at the position of the element for which fun returns false for the first time.

Examples

iex> Enum.split_while([1, 2, 3, 4], fn(x) -> x < 3 end)
{[1, 2], [3, 4]}

split_with(enumerable, fun)

split_with(t, (element -> any)) :: {list, list}

Splits the enumerable in two lists according to the given function fun.

Splits the given enumerable in two lists by calling fun with each element in the enumerable as its only argument. Returns a tuple with the first list containing all the elements in enumerable for which applying fun returned a truthy value, and a second list with all the elements for which applying fun returned a falsey value (false or nil).

The elements in both the returned lists are in the same relative order as they were in the original enumerable (if such enumerable was ordered, e.g., a list); see the examples below.

Examples

iex> Enum.split_with([5, 4, 3, 2, 1, 0], fn(x) -> rem(x, 2) == 0 end)
{[4, 2, 0], [5, 3, 1]}

iex> Enum.split_with(%{a: 1, b: -2, c: 1, d: -3}, fn({_k, v}) -> v < 0 end)
{[b: -2, d: -3], [a: 1, c: 1]}

iex> Enum.split_with(%{a: 1, b: -2, c: 1, d: -3}, fn({_k, v}) -> v > 50 end)
{[], [a: 1, b: -2, c: 1, d: -3]}

iex> Enum.split_with(%{}, fn({_k, v}) -> v > 50 end)
{[], []}

sum(enumerable)

sum(t) :: number

Returns the sum of all elements.

Raises ArithmeticError if enumerable contains a non-numeric value.

Examples

iex> Enum.sum([1, 2, 3])
6

take(enumerable, count)

take(t, integer) :: list

Takes the first count items from the enumerable.

count must be an integer. If a negative count is given, the last count values will be taken. For such, the enumerable is fully enumerated keeping up to 2 * count elements in memory. Once the end of the enumerable is reached, the last count elements are returned.

Examples

iex> Enum.take([1, 2, 3], 2)
[1, 2]

iex> Enum.take([1, 2, 3], 10)
[1, 2, 3]

iex> Enum.take([1, 2, 3], 0)
[]

iex> Enum.take([1, 2, 3], -1)
[3]

take_every(enumerable, nth)

take_every(t, non_neg_integer) :: list

Returns a list of every nth item in the enumerable, starting with the first element.

The first item is always included, unless nth is 0.

The second argument specifying every nth item must be a non-negative integer.

Examples

iex> Enum.take_every(1..10, 2)
[1, 3, 5, 7, 9]

iex> Enum.take_every(1..10, 0)
[]

iex> Enum.take_every([1, 2, 3], 1)
[1, 2, 3]

take_random(enumerable, count)

take_random(t, non_neg_integer) :: list

Takes count random items from enumerable.

Notice this function will traverse the whole enumerable to get the random sublist.

See random/1 for notes on implementation and random seed.

Examples

# Although not necessary, let's seed the random algorithm
iex> :rand.seed(:exsplus, {1, 2, 3})
iex> Enum.take_random(1..10, 2)
[5, 4]
iex> Enum.take_random(?a..?z, 5)
'ipybz'

take_while(enumerable, fun)

take_while(t, (element -> as_boolean(term))) :: list

Takes the items from the beginning of the enumerable while fun returns a truthy value.

Examples

iex> Enum.take_while([1, 2, 3], fn(x) -> x < 3 end)
[1, 2]

to_list(enumerable)

to_list(t) :: [element]

Converts enumerable to a list.

Examples

iex> Enum.to_list(1..3)
[1, 2, 3]

uniq(enumerable)

uniq(t) :: list

Enumerates the enumerable, removing all duplicated elements.

Examples

iex> Enum.uniq([1, 2, 3, 3, 2, 1])
[1, 2, 3]

uniq_by(enumerable, fun)

uniq_by(t, (element -> term)) :: list

Enumerates the enumerable, by removing the elements for which function fun returned duplicate items.

The function fun maps every element to a term. Two elements are considered duplicates if the return value of fun is equal for both of them.

The first occurrence of each element is kept.

Example

iex> Enum.uniq_by([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end)
[{1, :x}, {2, :y}]

iex> Enum.uniq_by([a: {:tea, 2}, b: {:tea, 2}, c: {:coffee, 1}], fn {_, y} -> y end)
[a: {:tea, 2}, c: {:coffee, 1}]

unzip(enumerable)

unzip(t) :: {[element], [element]}

Opposite of Enum.zip/2; extracts a two-element tuples from the enumerable and groups them together.

It takes an enumerable with items being two-element tuples and returns a tuple with two lists, each of which is formed by the first and second element of each tuple, respectively.

This function fails unless enumerable is or can be converted into a list of tuples with exactly two elements in each tuple.

Examples

iex> Enum.unzip([{:a, 1}, {:b, 2}, {:c, 3}])
{[:a, :b, :c], [1, 2, 3]}

iex> Enum.unzip(%{a: 1, b: 2})
{[:a, :b], [1, 2]}

with_index(enumerable, offset \\ 0)

with_index(t, integer) :: [{element, index}]

Returns the enumerable with each element wrapped in a tuple alongside its index.

If an offset is given, we will index from the given offset instead of from zero.

Examples

iex> Enum.with_index([:a, :b, :c])
[a: 0, b: 1, c: 2]

iex> Enum.with_index([:a, :b, :c], 3)
[a: 3, b: 4, c: 5]

zip(enumerables)

zip([t]) :: t

Zips corresponding elements from a collection of enumerables into one list of tuples.

The zipping finishes as soon as any enumerable completes.

Examples

iex> Enum.zip([[1, 2, 3], [:a, :b, :c], ["foo", "bar", "baz"]])
[{1, :a, "foo"}, {2, :b, "bar"}, {3, :c, "baz"}]

iex> Enum.zip([[1, 2, 3, 4, 5], [:a, :b, :c]])
[{1, :a}, {2, :b}, {3, :c}]

zip(enumerable1, enumerable2)

zip(t, t) :: [{any, any}]

Zips corresponding elements from two enumerables into one list of tuples.

The zipping finishes as soon as any enumerable completes.

Examples

iex> Enum.zip([1, 2, 3], [:a, :b, :c])
[{1, :a}, {2, :b}, {3, :c}]

iex> Enum.zip([1, 2, 3, 4, 5], [:a, :b, :c])
[{1, :a}, {2, :b}, {3, :c}]

© 2012–2017 Plataformatec
Licensed under the Apache License, Version 2.0.
https://hexdocs.pm/elixir/1.5.0/Enum.html