在数学与计算机科学中,至少具备以下特征之一的
- 拥有一个或多个函数类型的参数;
- 返回值是一个函数;
就是,high-order function 高阶函数。
与之对应的是 first-order functions,即普通函数。
高阶函数在数学中也称之为: operators) or functionals)
函数式编程中会大量使用高阶函数。
常用的高阶函数有:
map/sort/filter/…
JavaScript 高阶函数示例:
const twice = (f, v) => f(f(v));
const add3 = v => v + 3;
twice(add3, 7); // 13
PHP 高阶函数示例:
$twice = function($f, $v) {
return $f($f($v));
};
$f = function($v) {
return $v + 3;
};
echo($twice($f, 7)); // 13
C 高阶函数示例:
#include <stdio.h>
typedef int (*int_func_int) (int);
int add3(int x) {
return x + 3;
}
int twice(int_func_int f, int v) {
return f(f(v));
}
int main() {
printf("%d\n”, twice(add3, 7) );
return 0;
}