Skip to content
Elixir

Операции Enum и Stream

Функциональные операции над коллекциями в Elixir.

#enum#stream#functional

Code

elixir
# Map / Filter / Reduce
[1, 2, 3, 4, 5]
|> Enum.map(fn x -> x * x end)         # [1, 4, 9, 16, 25]
|> Enum.filter(fn x -> x > 5 end)      # [9, 16, 25]
|> Enum.reduce(0, fn x, acc -> acc + x end)  # 50

# Common operations
Enum.sum(1..100)                    # 5050
Enum.count([1, 2, 3, 4])           # 4
Enum.min_max([3, 1, 4, 1, 5])      # {1, 5}
Enum.uniq([1, 1, 2, 2, 3])         # [1, 2, 3]
Enum.sort([3, 1, 2])               # [1, 2, 3]
Enum.chunk_every([1,2,3,4,5], 2)   # [[1, 2], [3, 4], [5]]

# Find / any? / all?
Enum.find([1, 2, 3], fn x -> x > 2 end)        # 3
Enum.any?([1, 2, 3], fn x -> x > 2 end)        # true
Enum.all?([1, 2, 3], fn x -> x > 0 end)        # true

# Group / partition
Enum.group_by(["a", "bb", "c", "dd"], &String.length/1)
# %{1 => ["a", "c"], 2 => ["bb", "dd"]}

Enum.partition([1, 2, 3, 4, 5], fn x -> x > 2 end)
# {[3, 4, 5], [1, 2]}

# Comprehension
for x <- 1..3, y <- 1..3, x <= y, do: {x, y}
# [{1, 1}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {3, 3}]