0

I am trying to understand exactly how this function operates and cannot figure it out in my brain. Please can you show the step-by-step process of the code?

I've been sitting here trying to figure this example out in my head using a calculator on my computer and running through the code many many times in my head, but it just doesn't add up. Pun not intended.

constructor(values) {
  this.values = values || []
}

const list = new List([1,2,3,4])

expect(list.foldl((acc, el) => el / acc, 24)).toEqual(64);

foldl(fn, initialValue) {
  let acc = initialValue;
  for (let i in this.values) {
    acc = fn(acc, this.values[i]);

  }
  return acc; // 64... HOW??!
}

Okay here's how I run through it in my head. Please can you explain to me why I'm wrong, and show me what is correct in pseudocode as I've done below.

```
// accumulator is 24 and therefore we divide the first element of the array which is 1 by 24 which equals .041666667

// the accumulator now ACCUMULATES which means 24 plus .041666667 is equal to 24.041666667

// now the accumulator is 24.041666667 and we divide the second element of the array which is 2 by 24 which equals .083333333

// the accumulator which is 24.041666667 now adds .083333333 which equals 24.874999997

// now the accumulator is 24.874999997 and we divide the third element of the array which is 3 by 24.874999997 which equals .120603015 

and so on...

What am I missing here?

Leafyshark
  • 395
  • 2
  • 5
  • 11
  • 2
    The accumulator only sums the values if you tell it to. Your example does not do that. `acc` becomes the result of `el / acc`, **not** `acc + (el / acc)`. Check out [**this demonstration**](https://jsfiddle.net/ejvcpxr8/) which logs the values at each step. (It uses `reduce`, but simulates the behavior) – Tyler Roper Jun 19 '19 at 20:43
  • Ahh I see, yes this is great way of showing it. Appreciate your example, thank you! – Leafyshark Jun 19 '19 at 20:55
  • 1
    [Don't use `for…in` enumerations on arrays!](https://stackoverflow.com/q/500504/1048572) – Bergi Jun 19 '19 at 21:09

1 Answers1

1

Accumulating doesn't mean adding. It means running the function that you passed into foldl. Also, the value of 24 is only used the first time; after that, the accumulation means that it uses the return value from last time. Here's the correct sequence of values:

acc = 24
el = 1
acc = 1/24
el = 2
acc = 2/(1/24) = 48
el = 3
acc = 3/48 = 1/16
el = 4
acc = 4/(1/16) = 64