Elixir reduces the order of elements

Trying to understand how Elixir makes Enum.reduce, I connected it to look at the output. I don’t understand why it first executes the second element of the list, and not the first, and then it executes all the rest independently.

iex (30)> Enum.reduce([1,2,3,4], &(IO.puts("a#{&1} b#{&2}")))
a2 b1
a3 bok
a4 bok

(A and b to check order)

Looking at the source, I think it translates into

:lists.foldl(&IO.puts("a#{&1} b#{&2}"), 1, [2,3,4])

giving the same result.

where 1 is the initial battery, and if I gave him a function that gave him something to copy, I would say something interesting, except for the "side".

Inverting these initial values, however, strikes me as an odd behavior. How should I think about decreasing the implementation?

+4
source share
2 answers

Enum.reduce/2. . h Enum.reduce/2 iex.

Invokes fun for each element in the collection passing that element and the
accumulator acc as arguments. fun 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

.

,    , n - 1 , n -    .

+3

Enum.reduce, Enum.reduce/2 Enum.reduce/3. Enum.reduce/3 - . Enum.reduce/2 /3, , : def reduce([first|rest], fun), do: reduce(rest, first, fun).

+2

Source: https://habr.com/ru/post/1616152/


All Articles