[英]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. 您正在fold1函数中执行newAccumulator。 Pass in newAccumulator instead of newAccumulator(); 传递newAccumulator而不是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
的调用中,调用newAccumulator
函数:
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. 在第二种情况下,对newAccumulator
的调用不会返回任何内容,因此foldl
没有可以调用以计算总和的函数。
You should pass newAccummulator directly to foldl
, not the value it (doesn't) return: 您应该将newAccummulator直接传递给foldl
,而不是它(不)返回的值:
foldl([1, 2, 3, 4], newAccumulator);
The second doesn't work because you aren't passing foldl a function. 第二个无效,因为您没有传递foldl函数。
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. 在第一个示例中,您执行newAccumulator,newAccumulator返回一个函数,该函数将传递给foldl ... Foldl使用该函数对数字求和。
In the second example, you execute newAccumulator and pass the result, but the result of newAccumulator is not a function. 在第二个示例中,您执行newAccumulator并传递结果,但是newAccumulator的结果不是函数。
Also, the function you've named foldl is usually called 'foreach'. 同样,您将其命名为foldl的函数通常称为“ 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. Foldl通常会通过采用将数字加到总数中并返回新总数的函数本身来累积总数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.