簡體   English   中英

首先總結,第二不->為什么?

[英]First sums, second doesn't -> why?

<!-- first -->
<script>
var total = 0;
var newAccumulator = function()
{
  return function(i) { total += i; };
}

var foldl = function(arr, putNum)
{
  for (var i = 0; i < arr.length; ++i)
  {
    putNum(arr[i]);
  }
}

foldl([1, 2, 3, 4], newAccumulator());
document.write("Sum: " + total + "<br/>");
</script>

<!-- second -->
<script>
var total = 0;
var newAccumulator = function(i)
{
  total += i;
}

var foldl = function(arr, putNum)
{
  for (var i = 0; i < arr.length; ++i)
  {
    putNum(arr[i]);
  }
}

foldl([1, 2, 3, 4], newAccumulator());
document.write("Sum: " + total + "<br/>");
</script>

它認為你想要

 foldl([1, 2, 3, 4], newAccumulator);

在第二次通話中

您正在fold1函數中執行newAccumulator。 傳遞newAccumulator而不是newAccumulator();

foldl([1, 2, 3, 4], newAccumulator());

foldl([1, 2, 3, 4], newAccumulator);

在對foldl的調用中,調用newAccumulator函數:

foldl([1, 2, 3, 4], newAccumulator());

在第一種情況下,這將返回一個求和的函數:

return function(i) { total += i; };

在第二種情況下,對newAccumulator的調用不會返回任何內容,因此foldl沒有可以調用以計算總和的函數。
您應該將newAccummulator直接傳遞給foldl ,而不是它(不)返回的值:

foldl([1, 2, 3, 4], newAccumulator);

第二個無效,因為您沒有傳遞foldl函數。

在第一個示例中,您執行newAccumulator,newAccumulator返回一個函數,該函數將傳遞給foldl ... Foldl使用該函數對數字求和。

在第二個示例中,您執行newAccumulator並傳遞結果,但是newAccumulator的結果不是函數。

同樣,您將其命名為foldl的函數通常稱為“ foreach”。 如果將結果存儲在數組中,則可能稱為“地圖”。 Foldl通常會通過采用將數字加到總數中並返回新總數的函數本身來累積總數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM