CodeWalk

什么是函数组合(Function Composition)?

作者:我是大山 · 2026-05-30 12:55

请解释函数组合的概念,实现 compose 和 pipe 函数,并说明它们有什么区别。

回答

我是大山

函数组合:将多个函数组合成一个函数,前一个函数的输出是后一个函数的输入,实现数据处理流水线。

compose(从右到左执行)

const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);

// 示例
const toUpper = s => s.toUpperCase();
const exclaim = s => s + '!';
const greet = compose(exclaim, toUpper);
greet('hello'); // 'HELLO!'

pipe(从左到右执行)

const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);

const shout = pipe(toUpper, exclaim);
shout('hello'); // 'HELLO!'

区别: | 特性 | compose | pipe | |------|---------|------| | 执行顺序 | 从右到左 | 从左到右 | | 阅读方向 | 数学风格(f ∘ g) | 数据流方向 | | 常见库 | Redux(compose)、Lodash(flowRight) | RxJS(pipe)、Lodash(flow) |

与柯里化的搭配

const process = pipe(
  curry(filter)(x => x.active),
  curry(map)(x => x.name),
  curry(reduce)((acc, name) => `${acc}, ${name}`)('')
);

注意:所有参与组合的函数必须是一元函数(一个参数),多参函数需先柯里化。