Enum是一个非常有用的模块,提供了一组处理可枚举对象的算法。它可以:
sort/2、sort_by/2)、filter/2)、group_by/3)、count/2)find/3)、min/3、max/3)、reduce/3、reduce_while/3)、还有更多!完整列表请参考 Enum 模块文档。
一般来说,_可枚举对象_是任何可以被迭代的数据,也就是集合。在 Elixir 中,可枚举对象是任何实现了Enumerable协议的数据类型。包括:
如果这些你还不全认识,也不用担心。
任何人都可以为自己自定义的数据结构实现Enumerable协议。
Enum.reduce/2可以把整个可枚举对象_归约_为单个值。要做到这一点,需要用到一种特殊的变量,叫做_累加器_。累加器在每次迭代之间携带归约的中间状态。这让它成为处理可枚举对象最强大的函数之一。许多其他专门的函数都可以用更通用的reduce来替代。例如……
找出最大值:
Enum.max([4, 20, 31, 9, 2])
# => 31
Enum.reduce([4, 20, 31, 9, 2], nil, fn x, acc ->
cond do
acc == nil -> x
x > acc -> x
x <= acc -> acc
end
end)
# => 31
甚至还能做映射(但之后需要把结果反转过来):
Enum.map([1, 2, 3, 4, 5], fn x -> x + 10 end)
# => [11, 12, 13, 14, 15]
Enum.reduce([1, 2, 3, 4, 5], [], fn x, acc -> [x + 10 | acc] end)
# => [15, 14, 13, 12, 11]
使用 Map.new/2:
%{a: 1, b: 2}
|> Map.new(fn {key, value} -> {key, value * 10} end)
使用 Enum.into/3:
%{a: 1, b: 2}
|> Enum.into(%{}, fn {key, value} -> {key, value * 10} end)
使用 Enum.map/2:
%{a: 1, b: 2}
|> Enum.map(fn {key, value} -> {key, value * 10} end)
|> Enum.into(%{})