I'm reading the Elixir docs and I come across this 'foldr' function for the Elixir List module. I'm really having a tough time understanding it. Here is what the doc says:
Folds (reduces) the given list from the right with a function. Requires an accumulator.
iex> List.foldr([1, 2, 3, 4], 0, fn(x, acc) -> x - acc end)
-2
So this should return -2. But when I read it, I seem to think that it is trying to minus a number by 0 every time, and if that is the case how do we get -2? I clearly don't understand the accumulator, can someone break it down for me?
The easiest way to understand how such functions work is to stick in an IO.puts call with all the arguments.
iex(1)> List.foldr([1, 2, 3, 4], 0, fn(x, acc) -> IO.puts "#{x} - #{acc} = #{x - acc}"; x - acc end)
4 - 0 = 4
3 - 4 = -1
2 - -1 = 3
1 - 3 = -2
-2
So, in the first iteration, x is 4 and acc is 0, and we get x - acc = 4 - 0 = 4. Finally we end up with -2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With