Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.foldr or List.foldl understanding with Elixir

Tags:

elixir

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:

DOCS

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?

like image 945
Bitwise Avatar asked Jan 01 '26 15:01

Bitwise


1 Answers

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.

like image 150
Dogbert Avatar answered Jan 06 '26 12:01

Dogbert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!