Difficulty understanding a program

Hi,

I am going through a program in which we are given a list, let’s say

list = [1, 2, 3, 4, 5, 6]

Then the program should put the sum of that array and will repeat the process on the list tail until the list is empty. For example in the above given list:

[1, 2, 3, 4, 5, 6] = 21
[2, 3, 4, 5, 6] = 20
[3, 4, 5, 6] = 18
[4, 5, 6] = 15
[5, 6] = 11
[6] = 6
[] = 0

Here is the program that executes the above operation

Enum.scan([0 | list], Enum.sum(list), fn x, y -> y - x end)

I really don’t understand how the lambda function part work fn x, y -> y -x end

Thanks

This says that the anonymous function receives two arguments, x, y. The body of the function is y - x and since this is the last expression of the function, that value is returned. Perhaps easier to parse if you format it as fn(x,y) -> y - x end

Is it really the anonymous function that you have trouble understanding with?

It just subtracts one value from another. Where one value (x) is the current value from the input list and the other (y) is the return value from the previous call of the anonymous function.

How exactly it is working in the program … every time the head gets eliminated. what does y and x represent?

Can you kindly explain how the code is executing here?

so which value is x in the list let say we are considering list = [1, 2, 3, 4, 5, 6] and how it gets reduced to list = [2, 3, 4, 5, 6]. I really dont understand this.

Ok so Enum.scan/3 will iterate through the list provided as the first argument, and it’ll build up a reducer as it goes. At each step, the function will store the current reducer value in a list, and return that list at the end. The second argument is what the reducer should start as. Ok, so let’s step through an example.

At the beginning, we’re starting our reducer with the value Enum.sum(list), which equals 21. Then we start iterating through our list. The 21 gets passed to the function as the second argument, and the value from the list gets passed as the first. The first element in the list is a 0, so our first iteration looks like this:
X = 0
Y = 21
21 - 0 = 21
[21]
The result of the computation y - x is stored in the list and used as the accumulator for the next iteration. Let’s keep stepping through:
X = 1
Y = 21
21 - 1 = 20
[21, 20]

X = 2
Y = 20
20 - 2 = 18
[21, 20, 18]

X = 3
Y = 18
18 - 3 = 15
[21, 20, 18, 15]

You can fill in the rest yourself but hopefully this helps you visualize what’s happening. You can also do something like this to more easily visualize it in iex:

Enum.scan([0 | list], Enum.sum(list), fn x, y ->
  IO.inspect(y, label: "y") - IO.inspect(x, label: "x")
end)
6 Likes

Thats a perfect explanation … Thank you so much.

You’re welcome! Happy to help. I’ve never actually used Enum.scan so I learned something new as well!