簡體   English   中英

有人可以用外行的方式向我解釋這個折疊示例嗎?

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

我試圖確切地了解此功能的運作方式,無法在我的大腦中弄清楚。 請您顯示代碼的逐步過程嗎?

我一直坐在這里,試圖使用計算機上的計算器在腦海中想出這個例子,並在腦海中多次運行該代碼,但這並沒有加總。 雙關語無用。

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??!
}

好的,這就是我腦海中的運行方式。 請您向我解釋為什么我錯了,並按照下面的步驟向我展示偽代碼中正確的地方。

```
// 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 

等等...

我在這里想念什么?

積累並不意味着增加。 這意味着運行傳遞給foldl的函數。 另外,值24僅在第一次使用。 之后,累加意味着它使用上次的返回值。 這是正確的值順序:

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