Conversation started Nov 29, 2019 at 7:39.
Nov 29, 2019 07:39
Yes
I can't get how it works
Do you understand what the reduce() function does?
Kinda but I don't understand well
It preform some function on each element of Iterable
Suppose you call reduce(fn, [1,2,3,4])
And at the end gives 1 output
@JohnRennie ok
What it does is take the first two elements of the list, 1 and 2, then calculate a = fn(1,2). Then it replaces those first two elements with a.
Nov 29, 2019 07:43
Ok
So the list starts [1,2,3,4] and changes to [a,3,4] where a = fn(1,2). OK so far?
But then it repeats. So it takes the first two elements again, now a and 3, and replaces them by b = fn(a,3).
So the list changes from [a,3,4] to [b,4] where b = fn(a,3)
Nov 29, 2019 07:46
Hmm ok
And then it repeats again so the list changes from [b,4] to [c] where c = fn(b,4)
So on
So only 1 element remains at the end
And now it stops because the list has length one, and it returns the value of the one remaining element in the list.
@Aladdin yes
So suppose the function fn(x,y) just added x and y together.
Aha ok
So we start with [1,2,3,4] and after the first iteraction we get a list one element shrter [1+2, 3, 4].
The it iterates again to give [(1+2) + 3, 4]
And then again to give [((1+2)+3) + 4]
Nov 29, 2019 07:50
Got it
Makes, sense
Then it stops because the list now only has a single element, and it returns that value i.e. 1+2+3+4
How will u find maximum in a list using this
Well let's try. Suppose we do reduce(max, [1,2,3,4])
On the first iteration it takes the first two elements, 1 and 2, and does max(1,2) to get the result 2. So the list now looks like [2,3,4].
Then the next iteration does max(2,3) to give 3 so the list reduces to [3,4]
Ok
Next we get 4
And the last iteration gives [4] so it returns 4
@Aladdin yes
So this is a way of getting the maximum value in the list, though it's a rather strange way of getting the maximum.
Nov 29, 2019 07:55
@JohnRennie my teacher said something like we can do like reduce(fun, Iterable, 2)
So it will start with 2 and first element of Iterable
The reason you're being taught this is that it's a technique called functional programming. This is kind of trendy at the moment, though I have to confess I don't know much about it.
What's use of functional programming
@Aladdin In effect it prefixes the list with the last argument.
Didn't understand
So if you call reduce(fn, [1,2,3,4], 5) it's like calling reduce(fn, [5,1,2,3,4])
 
Conversation ended Nov 29, 2019 at 7:57.