简体   繁体   中英

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>

It think you want

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

In the second call

You are executing newAccumulator in the fold1 function. Pass in newAccumulator instead of newAccumulator();

old

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

new

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

In the call to foldl you call the newAccumulator function:

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

In the first case this returns a function that does the summing up:

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

In the second case the call to newAccumulator doesn't return anything, so foldl doesn't have a function it can call to calculate the sum.
You should pass newAccummulator directly to foldl , not the value it (doesn't) return:

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

The second doesn't work because you aren't passing foldl a function.

In the first example, you execute newAccumulator, and newAccumulator returns a function, which is passed to foldl... Foldl uses that function to sum the numbers.

In the second example, you execute newAccumulator and pass the result, but the result of newAccumulator is not a function.

Also, the function you've named foldl is usually called 'foreach'. If you stored the results in an array it might be called 'map'. Foldl would normally accumulate the total itself by taking a function that adds the number to the total and returns the new total.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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