Elixir:reduce over 列表,其中 reducer 函数接受迭代列表的子集作为参数
Elixir: reduce over list where the reducer function takes in the subset of the list iterated over so far as a parameter
Enum.reduce
中的函数用下一个元素和累加器调用。我想要这个,但是对于下一个元素,reducer 应该接受到目前为止迭代的列表的子集。
Enum.reduce/3
中的累加器可能是任何东西,因此可能会收集已经访问过的元素。有点像下面应该工作(未经测试)。
[1, 2, 3]
|> Enum.reduce({[], 0}, fn e, {head, acc} ->
head = head ++ [e]
acc = acc + Enum.sum(head)
{head, acc}
end)
|> elem(1)
#⇒ 10
结果应该是10
,因为我们加了3次1
,加了2次2
,加了1次3
。
Enum.reduce
中的函数用下一个元素和累加器调用。我想要这个,但是对于下一个元素,reducer 应该接受到目前为止迭代的列表的子集。
Enum.reduce/3
中的累加器可能是任何东西,因此可能会收集已经访问过的元素。有点像下面应该工作(未经测试)。
[1, 2, 3]
|> Enum.reduce({[], 0}, fn e, {head, acc} ->
head = head ++ [e]
acc = acc + Enum.sum(head)
{head, acc}
end)
|> elem(1)
#⇒ 10
结果应该是10
,因为我们加了3次1
,加了2次2
,加了1次3
。