降低

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, []