Elixir 减少元素的顺序
Elixir reduce order of elements
为了了解 Elixir 的工作原理 Enum.reduce,我将其插入一个 puts 以观察输出。我不清楚为什么它首先执行第二个列表元素,而不是第一个,然后独立地执行所有其他元素。
iex (30)> Enum.reduce([1,2,3,4], &(IO.puts("a#{&1} b#{&2}")))
a2 b1
a3 bok
a4 bok
(a 和 b 只是为了验证订单)
查看源代码,我认为它翻译成
:lists.foldl(&IO.puts("a#{&1} b#{&2}"), 1, [2,3,4])
产生相同的结果。
其中 1 是初始累加器,如果我给它一个函数来累加它,它会说一些有趣的东西,而不是 "bok"。
不过,反转这些初始值让我觉得很奇怪。我应该如何考虑 Reduce 实施?
有两个 Enum.reduce
函数,Enum.reduce/2
和 Enum.reduce/3
。 Enum.reduce/3
是通常的 reduce 函数,采用可枚举的初始累加器和归约函数。 Enum.reduce/2
与 /3
非常相似,但跳过了初始累加器,而是将可枚举中的第一个元素作为累加器,对于列表,它可以实现为:def reduce([first|rest], fun), do: reduce(rest, first, fun)
.
您正在使用 Enum.reduce/2 函数。它将列表的第一个元素视为累加器。只需在 iex 中输入 h Enum.reduce/2
。您将获得以下输出
Invokes fun for each element in the collection passing that element and the
accumulator acc as arguments. fun's return value is stored in acc. The first
element of the collection is used as the initial value of acc. If you wish to
use another value for acc, use Enumerable.reduce/3. This function won't call
the specified function for enumerables that are 1-element long. Returns the
accumulator.
Note that since the first element of the enumerable is used as the initial
value of the accumulator, fun will only be executed n - 1 times where n is the
length of the enumerable.
Examples
┃ iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end)
┃ 24
第二段应该可以澄清你的疑问
请注意,由于枚举的第一个元素用作初始
累加器的值,fun 只会执行 n - 1 次,其中 n 是
可枚举的长度。
为了了解 Elixir 的工作原理 Enum.reduce,我将其插入一个 puts 以观察输出。我不清楚为什么它首先执行第二个列表元素,而不是第一个,然后独立地执行所有其他元素。
iex (30)> Enum.reduce([1,2,3,4], &(IO.puts("a#{&1} b#{&2}")))
a2 b1
a3 bok
a4 bok
(a 和 b 只是为了验证订单)
查看源代码,我认为它翻译成
:lists.foldl(&IO.puts("a#{&1} b#{&2}"), 1, [2,3,4])
产生相同的结果。
其中 1 是初始累加器,如果我给它一个函数来累加它,它会说一些有趣的东西,而不是 "bok"。
不过,反转这些初始值让我觉得很奇怪。我应该如何考虑 Reduce 实施?
有两个 Enum.reduce
函数,Enum.reduce/2
和 Enum.reduce/3
。 Enum.reduce/3
是通常的 reduce 函数,采用可枚举的初始累加器和归约函数。 Enum.reduce/2
与 /3
非常相似,但跳过了初始累加器,而是将可枚举中的第一个元素作为累加器,对于列表,它可以实现为:def reduce([first|rest], fun), do: reduce(rest, first, fun)
.
您正在使用 Enum.reduce/2 函数。它将列表的第一个元素视为累加器。只需在 iex 中输入 h Enum.reduce/2
。您将获得以下输出
Invokes fun for each element in the collection passing that element and the
accumulator acc as arguments. fun's return value is stored in acc. The first
element of the collection is used as the initial value of acc. If you wish to
use another value for acc, use Enumerable.reduce/3. This function won't call
the specified function for enumerables that are 1-element long. Returns the
accumulator.
Note that since the first element of the enumerable is used as the initial
value of the accumulator, fun will only be executed n - 1 times where n is the
length of the enumerable.
Examples
┃ iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end)
┃ 24
第二段应该可以澄清你的疑问
请注意,由于枚举的第一个元素用作初始 累加器的值,fun 只会执行 n - 1 次,其中 n 是 可枚举的长度。