Elixir v1.1.0 Enum

Provides a set of algorithms that enumerate over collections according to the Enumerable protocol:

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

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

iex> dict = %{a: 1, b: 2}
iex> Enum.map(dict, 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 collection. The Stream module allows lazy enumeration of collections and provides infinite streams.

Since the majority of the functions in Enum enumerate the whole collection 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

Functions

Invokes the given fun for each item in the collection and returns false if at least one invocation returns false or nil. Otherwise returns true

Invokes the given fun for each item in the collection and returns true if at least one invocation returns a truthy value. Returns false otherwise

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

Shortcut to chunk(collection, n, n)

Returns a collection of lists containing n items each, where each new chunk starts step elements into the collection

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

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

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

Returns the collection’s size

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

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

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

Drops the first count items from collection

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

Invokes the given fun for each item in the collection. Returns :ok

Returns true if the collection is empty, otherwise false

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

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

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

Filters the collection and maps its values in one pass

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

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

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

Returns a new collection appending the result of invoking fun on each corresponding item of collection

Maps and reduces a collection, flattening the given results

Splits collection into groups based on fun

Intersperses element between each element of the enumeration

Inserts the given enumerable into a collectable

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

Joins the given collection into a binary using joiner as a separator. If joiner is not passed at all, it defaults to the empty binary

Returns a new collection, where each item is the result of invoking fun on each corresponding item of collection

Maps and joins the given collection 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

Invokes the given fun for each item in the collection while also keeping an accumulator. Returns a tuple where the first element is the mapped collection and the second one is the final accumulator

Returns the maximum value. Raises EmptyError if the collection is empty

Returns the maximum value as calculated by the given function. Raises EmptyError if the collection is empty

Checks if value exists within the collection

Returns the minimum value. Raises EmptyError if the collection is empty

Returns the minimum value as calculated by the given function. Raises EmptyError if the collection is empty

Returns a tuple with the minimum and maximum values. Raises EmptyError if the collection is empty

Returns a tuple with the minimum and maximum values as calculated by the given function. Raises EmptyError if the collection is empty

Partitions collection into two collections, where the first one contains elements for which fun returns a truthy value, and the second one — for which fun returns false or nil

Returns a random element of a collection. Raises EmptyError if the collection is empty

Invokes fun for each element in the collection passing that element and the accumulator acc as arguments. fun’s return value is stored in acc. The first element of the collection is used as the initial value of acc. If you wish to use another value for acc, use Enumerable.reduce/3. This function won’t call the specified function for enumerables that are 1-element long. Returns the accumulator

Invokes fun for each element in the collection passing that element and the accumulator acc as arguments. fun’s return value is stored in acc. Returns the accumulator

Reduces the collection until halt is emitted

Returns elements of collection for which fun returns false or nil

Reverses the collection

Reverses the collection and appends the tail. This is an optimization for Enum.concat(Enum.reverse(collection), tail)

Reverses the collection in the range from initial position first through count elements. If count is greater than the size of the rest of the collection, then this function will reverse the rest of the collection

Applies the given function to each element in the collection, storing the result in a list and passing it as the accumulator for the next computation

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

Returns a list of collection elements shuffled

Returns a subset list of the given collection. Drops elements until element position range.first, then takes elements until element position range.last (inclusive)

Returns a subset list of the given collection. Drops elements until element position start, then takes count elements

Sorts the collection according to Elixir’s term ordering

Sorts the collection by the given function

Sorts the mapped results of the collection according to the sorter function

Splits the enumerable into two collections, leaving count elements in the first one. If count is a negative number, it starts counting from the back to the beginning of the collection

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

Returns the sum of all values

Takes the first count items from the collection

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

Takes random items from a collection

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

Converts collection to a list

Enumerates the collection, removing all duplicated elements

Enumerates the collection, removing all duplicated elements

Opposite of Enum.zip/2; takes a list of 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

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

Zips corresponding elements from two collections into one list of tuples

Types

default :: any
element :: any
index :: non_neg_integer

Functions

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

Specs

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

Invokes the given fun for each item in the collection and returns false if at least one invocation returns false or nil. Otherwise returns true.

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 collection are truthy values.

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

iex> Enum.all?([1, nil, 3])
false
any?(collection, fun \\ fn x -> x end)

Specs

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

Invokes the given fun for each item in the collection and returns true if at least one invocation returns a truthy value. Returns false otherwise.

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 collection is a truthy value.

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

iex> Enum.any?([false, true, false])
true
at(collection, n, default \\ nil)

Specs

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

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

Returns default if index is out of bounds.

Note this operation takes linear time. In order to access the element at index n, it will need to traverse n 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(collection, n)

Specs

chunk(t, pos_integer) :: [list]

Shortcut to chunk(collection, n, n).

chunk(collection, n, step, pad \\ nil)

Specs

chunk(t, pos_integer, pos_integer, t | nil) :: [list]

Returns a collection of lists containing n items each, where each new chunk starts step elements into the collection.

step is optional and, if not passed, defaults to n, i.e. chunks do not overlap. If the final chunk does not have n elements to fill the chunk, elements are taken as necessary from pad if it was passed. If pad is passed and does not have enough elements to fill the chunk, then the chunk is returned anyway with less than n elements. If pad is not passed at all or is nil, then the partial chunk is discarded from the result.

Examples

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

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

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

iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 3, [])
[[1, 2, 3], [4, 5, 6]]
chunk_by(collection, fun)

Specs

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

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

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]]
concat(enumerables)

Specs

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)

Specs

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

Specs

count(t) :: non_neg_integer

Returns the collection’s size.

Examples

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

Specs

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

Returns the count of items in the collection 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(collection)

Specs

dedup(t) :: list

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

Elements are compared using ===.

Examples

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

Specs

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

Enumerates the collection, 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, :x}, {2, :y}, {2, :z}, {1, :x}], fn {x, _} -> x end)
[{1, :x}, {2, :y}, {1, :x}]

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

Specs

drop(t, integer) :: list

Drops the first count items from collection.

If a negative value count is given, the last count values will be dropped. The collection 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_while(collection, fun)

Specs

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

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

Examples

iex> Enum.drop_while([1, 2, 3, 4, 5], fn(x) -> x < 3 end)
[3, 4, 5]
each(collection, fun)

Specs

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

Invokes the given fun for each item in the collection. Returns :ok.

Examples

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

Specs

empty?(t) :: boolean

Returns true if the collection is empty, otherwise false.

Examples

iex> Enum.empty?([])
true

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

Specs

fetch(t, integer) :: {: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 collection is enumerated once and the index is counted from the end (i.e. -1 fetches the last element).

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

Examples

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

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

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

Specs

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

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

Raises OutOfBoundsError if the given position is outside the range of the collection.

Note this operation takes linear time. In order to access the element at index n, it will need to traverse n 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(collection, fun)

Specs

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

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

Examples

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

Specs

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

Filters the collection and maps its values in one pass.

Examples

iex> Enum.filter_map([1, 2, 3], fn(x) -> rem(x, 2) == 0 end, &(&1 * 2))
[4]
find(collection, default \\ nil, fun)

Specs

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(collection, fun)

Specs

find_index(t, (element -> any)) :: index | 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(collection, default \\ nil, fun)

Specs

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(collection, fun)

Specs

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

Returns a new collection appending the result of invoking fun on each corresponding item of collection.

The given function should return an enumerable.

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]
flat_map_reduce(collection, acc, fun)

Specs

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

Maps and reduces a collection, flattening the given results.

It expects an accumulator and a function that receives each stream item and an accumulator, and must return a tuple containing a new stream (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}
group_by(collection, dict \\ %{}, fun)

Specs

group_by(t, dict, (element -> any)) :: dict when dict: Dict.t

Splits collection into groups based on fun.

The result is a dict (by default a map) where each key is a group and each value is a list of elements from collection for which fun returned that group. Ordering is not necessarily preserved.

Examples

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

Specs

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(collection, list)

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}
into(collection, list, transform)

Specs

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]
join(collection, joiner \\ "")

Specs

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

Joins the given collection 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 collection 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(collection, fun)

Specs

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

Returns a new collection, where each item is the result of invoking fun on each corresponding item of collection.

For dicts, 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_join(collection, joiner \\ "", mapper)

Specs

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

Maps and joins the given collection 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 in the collection 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(collection, acc, fun)

Specs

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

Invokes the given fun for each item in the collection while also keeping an accumulator. Returns a tuple where the first element is the mapped collection and the second one is the final accumulator.

For dicts, 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(collection)

Specs

max(t) :: element | no_return

Returns the maximum value. Raises EmptyError if the collection is empty.

Examples

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

Specs

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

Returns the maximum value as calculated by the given function. Raises EmptyError if the collection is empty.

Examples

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

Specs

member?(t, element) :: boolean

Checks if value exists within the collection.

Membership is tested with the match (===) operator, although enumerables like ranges may include floats inside the given range.

Examples

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

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

Specs

min(t) :: element | no_return

Returns the minimum value. Raises EmptyError if the collection is empty.

Examples

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

Specs

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

Returns the minimum value as calculated by the given function. Raises EmptyError if the collection is empty.

Examples

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

Specs

min_max(t) :: element | no_return

Returns a tuple with the minimum and maximum values. Raises EmptyError if the collection is empty.

Examples

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

Specs

min_max_by(t, (element -> any)) ::
  element |
  no_return

Returns a tuple with the minimum and maximum values as calculated by the given function. Raises EmptyError if the collection is empty.

Examples

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

Specs

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

Partitions collection into two collections, where the first one contains elements for which fun returns a truthy value, and the second one — for which fun returns false or nil.

Examples

iex> Enum.partition([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)
{[2], [1, 3]}
random(collection)

Specs

random(t) :: element

Returns a random element of a collection. Raises EmptyError if the collection is empty.

Notice that you need to explicitly call :random.seed/1 and set a seed value for the random algorithm. Otherwise, the default seed will be set which will always return the same result. For example, one could do the following to set a seed dynamically:

:random.seed(:os.timestamp)

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

Examples

iex> Enum.random([1, 2, 3])
1
iex> Enum.random([1, 2, 3])
2
reduce(collection, fun)

Specs

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

Invokes fun for each element in the collection passing that element and the accumulator acc as arguments. fun’s return value is stored in acc. The first element of the collection is used as the initial value of acc. If you wish to use another value for acc, use Enumerable.reduce/3. This function won’t call the specified function for enumerables that are 1-element long. Returns the accumulator.

Note that 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.

Examples

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

Specs

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

Invokes fun for each element in the collection passing that element and the accumulator acc as arguments. fun’s return value is stored in acc. Returns the accumulator.

Examples

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

Reduces the collection until halt is emitted.

The return value for fun is expected to be {:cont, acc}, return {:halt, acc} to end the reduction early. Returns the accumulator.

Examples

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

Specs

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

Returns elements of collection for which fun returns false or nil.

Examples

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

Specs

reverse(t) :: list

Reverses the collection.

Examples

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

Specs

reverse(t, t) :: list

Reverses the collection and appends the tail. This is an optimization for Enum.concat(Enum.reverse(collection), tail).

Examples

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

Specs

reverse_slice(t, non_neg_integer, non_neg_integer) :: list

Reverses the collection in the range from initial position first through count elements. If count is greater than the size of the rest of the collection, then this function will reverse the rest of the collection.

Examples

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

Specs

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

Applies the given function to each element in the collection, storing the result in a list and passing it as the accumulator for the next computation.

Examples

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

Specs

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

Applies the given function to each element in the collection, 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(collection)

Specs

shuffle(t) :: list

Returns a list of collection elements shuffled.

Notice that you need to explicitly call :random.seed/1 and set a seed value for the random algorithm. Otherwise, the default seed will be set which will always return the same result. For example, one could do the following to set a seed dynamically:

:random.seed(:os.timestamp)

Examples

iex> Enum.shuffle([1, 2, 3])
[3, 2, 1]
iex> Enum.shuffle([1, 2, 3])
[3, 1, 2]
slice(collection, range)

Specs

slice(t, Range.t) :: list

Returns a subset list of the given collection. Drops elements until element position range.first, then takes elements until element position range.last (inclusive).

Positions are calculated by adding the number of items in the collection to negative positions (so position -3 in a collection with count 5 becomes position 2).

The first position (after adding count to negative positions) must be smaller or equal to the last position.

If the start of the range is not a valid offset for the given collection or if the range is in reverse order, returns [].

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]

iex> Enum.slice(1..10, 11..20)
[]

iex> Enum.slice(1..10, 6..5)
[]
slice(collection, start, count)

Specs

slice(t, integer, non_neg_integer) :: list

Returns a subset list of the given collection. Drops elements until element position start, then takes count elements.

If the count is greater than collection length, it returns as much as possible. If zero, then it returns [].

Examples

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

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

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

Specs

sort(t) :: list

Sorts the collection according to Elixir’s term ordering.

Uses the merge sort algorithm.

Examples

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

Specs

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

Sorts the collection by the given function.

This function uses the merge sort algorithm. The given function must return false if the first argument is less than right 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:

iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) < byte_size(&2))
["of", "kind", "some", "monster"]
sort_by(collection, mapper, sorter \\ &<=/2)

Specs

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

Sorts the mapped results of the collection according to the sorter function.

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

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

This technique is also known as a Schwartzian Transform, or the Lisp decorate-sort-undecorate idiom as the mapper is decorating the original collection, then sorter is sorting the decorations, and finally the collection is being undecorated so only the original elements remain, but now in sorted order.

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(collection, count)

Specs

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

Splits the enumerable into two collections, leaving count elements in the first one. If count is a negative number, it starts counting from the back to the beginning of the collection.

Be aware that a negative count implies the collection 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(collection, fun)

Specs

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

Splits collection 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]}
sum(collection)

Specs

sum(t) :: number

Returns the sum of all values.

Raises ArithmeticError if collection contains a non-numeric value.

Examples

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

Specs

take(t, integer) :: list

Takes the first count items from the collection.

count must be an integer. If a negative count is given, the last count values will be taken. For such, the collection is fully enumerated keeping up to 2 * count elements in memory. Once the end of the collection 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(collection, nth)

Specs

take_every(t, non_neg_integer) :: list

Returns a collection of every nth item in the collection, 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, otherwise FunctionClauseError will be thrown.

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(collection, count)

Specs

take_random(t, integer) :: list

Takes random items from a collection.

Notice this function will traverse the whole collection to get the random sublist of collection. If you want the random number between two integers, the best option is to use the :random module.

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

Examples

iex> Enum.take_random(1..10, 2)
[1, 5]
iex> Enum.take_random(?a..?z, 5)
'tfesm'
take_while(collection, fun)

Specs

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

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

Examples

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

Specs

to_list(t) :: [term]

Converts collection to a list.

Examples

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

Specs

uniq(t) :: list

Enumerates the collection, removing all duplicated elements.

Examples

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

Specs

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

Enumerates the collection, removing all duplicated elements.

Example

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

Specs

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

Opposite of Enum.zip/2; takes a list of 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 collection 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(collection)

Specs

with_index(t) :: [{element, non_neg_integer}]

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

Examples

iex> Enum.with_index [1, 2, 3]
[{1, 0}, {2, 1}, {3, 2}]
zip(collection1, collection2)

Specs

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

Zips corresponding elements from two collections 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}]