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(%{})