Enum.reduce / 2 does not output IO

I am working with Enum.reduce and trying to add some debugging outputs to the reduction, but does not 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" 
+4
source share
1 answer

Enum.reduce/2 uses the first enumerated value as the initial accumulator. If the enumerated has only one element (for example, the nodes that you use), the function you pass to reduce/2 is never executed, because this first value is the accumulator, and there are no other values ​​left to decrease.

Admittedly, this is not listed in the docs for Enum.reduce/2 :

http://elixir-lang.org/docs/stable/elixir/Enum.html#reduce/2

but again, using the first value as the initial accumulator and at the same time reducing it will not make sense, since it will be "used" twice.

+5
source

All Articles