柯里化与偏函数
00:00
函数柯里化与偏函数应用
1. 柯里化(Currying)
1.1 定义
柯里化是将一个接受多个参数的函数转换为一系列只接受单个参数的函数:
f(a, b, c) → f(a)(b)(c)
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function (...moreArgs) {
return curried.apply(this, args.concat(moreArgs));
};
};
}
const add = curry((a, b, c) => a + b + c);
console.log(add(1)(2)(3)); // 6
console.log(add(1, 2)(3)); // 6
1.2 实际应用
// 日志函数
const log = curry((level, timestamp, message) => {
console.log(`[${level}] ${timestamp}: ${message}`);
});
const infoLog = log('INFO');
// 过滤器
const filter = curry((predicate, array) => array.filter(predicate));
const isEven = (n) => n % 2 === 0;
const filterEven = filter(isEven);
console.log(filterEven([1, 2, 3, 4, 5, 6])); // [2, 4, 6]
2. 偏函数(Partial Application)
function partial(fn, ...presetArgs) {
return function (...laterArgs) {
return fn(...presetArgs, ...laterArgs);
};
}
const greet = (greeting, name, punctuation) => `${greeting}, ${name}${punctuation}`;
const hello = partial(greet, 'Hello');
console.log(hello('World', '!')); // "Hello, World!"
3. 柯里化 vs 偏函数
| 特性 | 柯里化 | 偏函数 |
|---|---|---|
| 参数传递 | 每次一个 | 一次可多个 |
| 返回形式 | 链式单参函数 | 固定部分参数的函数 |
| 参数顺序 | 严格从左到右 | 可跳过(用占位符) |
| 适用场景 | 函数组合 | 固定配置参数 |