Enum.slice

You're seeing just the function slice, go back to Enum module for more information.
Link to this function

slice(enumerable, index_range)

View Source (since 1.6.0)

Specs

slice(t(), Range.t()) :: list()

Returns a subset list of the given enumerable by index_range.

index_range must be a Range. Given an enumerable, it drops elements before index_range.first (zero-base), then it takes elements until element index_range.last (inclusively).

Indexes are normalized, meaning that negative indexes will be counted from the end (for example, -1 means the last element of the enumerable).

If index_range.last is out of bounds, then it is assigned as the index of the last element.

If the normalized index_range.first is out of bounds of the given enumerable, or this one is greater than the normalized index_range.last, 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 indexes)
iex> Enum.slice(1..30, -5..-1)
[26, 27, 28, 29, 30]

For ranges where start > stop, you need to explicit mark them as increasing:

iex> Enum.slice(1..30, 25..-1//1)
[26, 27, 28, 29, 30]

If values are out of bounds, it returns an empty list:

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

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

slice(enumerable, start_index, amount)

View Source

Specs

slice(t(), index(), non_neg_integer()) :: list()

Returns a subset list of the given enumerable, from start_index (zero-based) with amount number of elements if available.

Given an enumerable, it drops elements right before element start_index; then, it takes amount of elements, returning as many elements as possible if there are not enough elements.

A negative start_index can be passed, which means the enumerable is enumerated once and the index is counted from the end (for example, -1 starts slicing from the last element).

It returns [] if amount is 0 or if start_index is out of bounds.

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)
[]

# using a negative start index
iex> Enum.slice(1..10, -6, 3)
[5, 6, 7]

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

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