# 列舉 (Enum)

## 列舉 (Enum)

`Enum` 模組包含超過 70 個可列舉 (enumerables) 的工作函數。我們在 previous lesson，中了解到的所有群集，除了元組之外，都為可列舉。

``````iex> Enum.__info__(:functions) |> Enum.each(fn({function, arity}) ->
...>   IO.puts "#{function}/#{arity}"
...> end)
all?/1
all?/2
any?/1
any?/2
at/2
at/3
...
``````

### all?

``````iex> Enum.all?(["foo", "bar", "hello"], fn(s) -> String.length(s) == 3 end)
false
iex> Enum.all?(["foo", "bar", "hello"], fn(s) -> String.length(s) > 1 end)
true
``````

### any?

``````iex> Enum.any?(["foo", "bar", "hello"], fn(s) -> String.length(s) == 5 end)
true
``````

### chunk_every

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

`chunk_every/4` 有幾個選項，但我們還不會深入了解它，查看 `the official documentation of this function` 來獲得更多資訊。

### chunk_by

``````iex> Enum.chunk_by(["one", "two", "three", "four", "five"], fn(x) -> String.length(x) end)
[["one", "two"], ["three"], ["four", "five"]]
iex> Enum.chunk_by(["one", "two", "three", "four", "five", "six"], fn(x) -> String.length(x) end)
[["one", "two"], ["three"], ["four", "five"], ["six"]]
``````

### map_every

``````# Apply function every three items
iex> Enum.map_every([1, 2, 3, 4, 5, 6, 7, 8], 3, fn x -> x + 1000 end)
[1001, 2, 3, 1004, 5, 6, 1007, 8]
``````

### each

``````iex> Enum.each(["one", "two", "three"], fn(s) -> IO.puts(s) end)
one
two
three
:ok
``````

: `each/2` 函數回傳 atom `:ok`

### map

``````iex> Enum.map([0, 1, 2, 3], fn(x) -> x - 1 end)
[-1, 0, 1, 2]
``````

### min

`min/1` 在群集中找到最小值：

``````iex> Enum.min([5, 3, 0, -1])
-1
``````

`min/2` 做同樣的事，但萬一列舉是空的，它允許我們指定一個函數來產生最小值。

``````iex> Enum.min([], fn -> :foo end)
:foo
``````

### max

`max/1` 回傳群集中的最大值：

``````iex> Enum.max([5, 3, 0, -1])
5
``````

`max/2` 相對 `max/1` 就如同 `min/2` 相對 `min/1` 一樣：

``````Enum.max([], fn -> :bar end)
:bar
``````

### reduce

``````iex> Enum.reduce([1, 2, 3], 10, fn(x, acc) -> x + acc end)
16

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

iex> Enum.reduce(["a","b","c"], "1", fn(x,acc)-> x <> acc end)
"cba1"
``````

### sort

`sort/1` 使用 Erlang 術語來排序確定的序列：

``````iex> Enum.sort([5, 6, 1, 3, -1, 4])
[-1, 1, 3, 4, 5, 6]

iex> Enum.sort([:foo, "bar", Enum, -1, 4])
[-1, 4, Enum, :foo, "bar"]
``````

`sort/2` 則允許我們提供自己的排序函數：

``````# with our function
iex> Enum.sort([%{:val => 4}, %{:val => 1}], fn(x, y) -> x[:val] > y[:val] end)
[%{val: 4}, %{val: 1}]

# without
iex> Enum.sort([%{:count => 4}, %{:count => 1}])
[%{count: 1}, %{count: 4}]
``````

### uniq_by

``````iex> Enum.uniq_by([1, 2, 3, 2, 1, 1, 1, 1, 1], fn x -> x end)
[1, 2, 3]
``````