Reputation: 3030
I am working with Enum.reduce
, and trying to add some debug outputs in the reduce, but it doesn't seem to output it in Enum.reduce/2
. Works as expected in Enum.reduce/3
.
nodes = [%{"value" => "x"}]
Enum.each(nodes, fn (node) ->
IO.puts "Each"
IO.inspect node["value"]
end)
Enum.reduce(nodes, fn (node, acc) ->
IO.puts "Reduce"
IO.inspect node["value"]
[node["value"], acc]
end)
Enum.reduce(nodes, [], fn (node, acc) ->
IO.puts "Pre-accumulator"
IO.inspect node["value"]
[node["value"], acc]
end)
When I run it I get the following:
Each
"x"
Pre-accumulator
"x"
Upvotes: 4
Views: 247
Reputation: 16801
Enum.reduce/2
uses the first value of the enumerable as the initial accumulator. If the enumerable only has one element (like the nodes
you're using), the function you pass to reduce/2
is never executed because that first value is the accumulator, and there are no other values left to reduce over.
The docs for Enum.reduce/2
explain it this way:
Since the first element of the enumerable is used as the initial value of the accumulator,
fun
will only be executedn - 1
times wheren
is the length of the enumerable. This function won't call the specified function for enumerables that are one-element long.
This makes sense, because using the first value as the initial accumulator and at the same time reducing over it wouldn't make sense as it would be "used" twice.
Upvotes: 5