简体   繁体   English

有人可以用外行的方式向我解释这个折叠示例吗?

[英]Can someone explain this foldl example to me in laymens terms?

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? 我在这里想念什么?

Accumulating doesn't mean adding. 积累并不意味着增加。 It means running the function that you passed into foldl . 这意味着运行传递给foldl的函数。 Also, the value of 24 is only used the first time; 另外,值24仅在第一次使用。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM