## 递归函数的高阶函数？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (12)

```function sum(a) {
if (a.length === 0) {
return 0;
} else {
return a[0] + sum(a.slice(1));
}
}```

```function logging(fn) {
return function(a) {
console.log(a);
return fn(a);
}
}

sum2 = logging(sum);
sum2([1, 2, 3]);```

```[1, 2, 3]
-> 6```

```[1, 2, 3]
[2, 3]
[3]
[]
-> 6```

```function sum_core(g) {
return function (a) {
if (a.length === 0) {
return 0;
} else {
return a[0] + g(a.slice(1));
}
};
}

sum = Y(sum_core);
sum([1, 2, 3]);
// -> 6```

### 2 个回答

```> traceSum([1, 2, 3]);
[1, 2, 3]
[2, 3]
[3]
[]
6```

```function traceSum(a) {
console.log(a);
if (a.length === 0) return 0;
else return a[0] + traceSum(a.slice(1));
}```

```function trace(f) {
return function (a) {
console.log(a);
return f(trace(f), a);
};
}```

```function y(f) {
return function (a) {
return f(y(f), a);
};
}```

```var traceSum = trace(function (traceSum, a) {
if (a.length === 0) return 0;
else return a[0] + traceSum(a.slice(1));
});```

```function sum(a) {
if (a.length === 0) return 0;
else return a[0] + sum(a.slice(1));
}```

```var obj = {
sum : function(a){
if (a.length === 0) {
return 0;
} else {
return a[0] + this.sum(a.slice(1)); // <-- dispatch on `this`
}
}
}