fp-ts中是否有内置方法实现返回TaskEither的函数动态组合?
动态链式组合TaskEither函数数组的fp-ts解决方案
在fp-ts中,无需自定义复杂reducer,通过**数组reduce方法结合TaskEither.chain**就能实现动态函数的顺序链式调用——这也是社区常用的常规方案。核心逻辑是将函数数组逐步累积为一个单一的TaskEither运算,每一步用chain衔接当前函数与前序结果。
实现示例
假设我们有如下函数数组:
import { TaskEither, right, left } from 'fp-ts/TaskEither'; // 示例:输入值加1 const add1 = (n: number): TaskEither<string, number> => right(n + 1); // 示例:输入值乘2 const multiplyBy2 = (n: number): TaskEither<string, number> => right(n * 2); // 示例:校验数值,负数则返回错误 const failIfNegative = (n: number): TaskEither<string, number> => n < 0 ? left('数值不能为负') : right(n); const taskFns: Array<(n: number) => TaskEither<string, number>> = [add1, multiplyBy2, failIfNegative];
用reduce组合函数并执行:
import { pipe } from 'fp-ts/function'; const runSequentialTasks = (initialValue: number, fns: typeof taskFns) => pipe( right(initialValue), // 将初始值包装为TaskEither类型 fns.reduce((accTask, currentFn) => accTask.chain(currentFn)) );
关键逻辑说明
reduce遍历函数数组,从包装后的初始值开始,每一步用chain将当前函数衔接至前序的TaskEither运算。- 若某一步函数返回
left(失败状态),整个链式调用会立即短路终止,符合TaskEither的故障处理特性。
简化写法
如果你偏好更紧凑的pipe风格,也可以直接用数组reduce完成累积:
const runSequentialTasks = (initialValue: number, fns: typeof taskFns) => fns.reduce((acc, fn) => acc.chain(fn), right(initialValue));
总结
fp-ts没有单独提供"动态链式组合"的专属函数,但通过**数组reduce + TaskEither.chain**的组合,就能优雅适配函数数量动态变化的场景,完全满足按顺序传递参数执行的需求。
内容的提问来源于stack exchange,提问作者PSF
相关产品推荐
相关产品推荐

