1. 组合(compose)与管道(pipe)如何实现无副作用的数据流
请解释组合(compose)与管道(pipe)如何实现无副作用的数据流?
- compose 与 pipe 的组合
- 纯函数与无副作用
- 数据流
- 纯函数:无副作用(不修改外部状态、不依赖可变外部、相同输入相同输出),是函数式数据流的基础。
- 组合(compose):
compose(f, g)(x) = f(g(x)),从右到左,把多个函数组合成一个函数,函数输出作为下一个函数输入。 - 管道(pipe):
pipe(f, g)(x) = g(f(x)),从左到右,f的输出流入g,数据像在管道中流动。 - 无副作用数据流:因为每个函数是纯函数,数据沿 compose/pipe 流动时,每个环节只做转换、不修改外部状态,输入输出清晰,可预测、可测试。数据流整条链由纯函数组成,无副作用。
- 应用:函数式编程中常用 compose/pipe 组合数据处理链(如集合处理、请求处理管线),实现"声明式数据流"。
compose/pipe 把纯函数组合成数据流,每个函数无副作用、输入输出清晰,数据沿链流动。纯函数保证无副作用,组合实现复用与声明式。
// 概念:pipe 组合(Java 函数式)
Function<Integer,Integer> inc = x -> x + 1;
Function<Integer,Integer> dbl = x -> x * 2;
Function<Integer,Integer> pipe = x -> dbl.apply(inc.apply(x)); // pipe(inc,dbl)
// compose: dbl(inc(x))
System.out.println(pipe.apply(3)); // 8