降低

Reduce 是一個函式,它將採用陣列,函式和累加器,並使用累加器作為種子,以第一個元素開始迭代,給出下一個累加器,並繼續對陣列中的所有元素進行迭代 (參見下面的示例)

defmodule MyList do
  def reduce([], _func, acc) do
    acc
  end

  def reduce([head | tail], func, acc) do
    reduce(tail, func, func.(acc, head))
  end
end

複製將以上程式碼段貼上到 iex 中:

  1. 要新增陣列中的所有數字:MyList.reduce [1,2,3,4], fn acc, element -> acc + element end, 0
  2. 多個陣列中的所有數字:MyList.reduce [1,2,3,4], fn acc, element -> acc * element end, 1

例 1 的解釋:

Iteration 1 => acc = 0, element = 1 ==> 0 + 1 ===> 1 = next accumulator
Iteration 2 => acc = 1, element = 2 ==> 1 + 2 ===> 3 = next accumulator
Iteration 3 => acc = 3, element = 3 ==> 3 + 3 ===> 6 = next accumulator
Iteration 4 => acc = 6, element = 4 ==> 6 + 4 ===> 10 = next accumulator = result(as all elements are done)

使用 reduce 過濾列表

MyList.reduce [1,2,3,4], fn acc, element -> if rem(element,2) == 0 do acc else acc ++ [element] end end, []