【问题标题】:merging 2 TaskEither in fp-ts在 fp-ts 中合并 2 个 TaskEither
【发布时间】:2022-01-07 12:00:36
【问题描述】:

我正在做一个使用fp-ts 的项目

我有 2 个 TaskEither 对象,例如 TaskEither, TaskEither

我想合并这些对象的内容并创建新的 TaskEither,
Example A object = {a: 123, b: 456, c: 0}

Example B object = {c: 789}

我想创建newObject: TaskEither<ErrorA, A>

如果一切顺利,期望值应该是{a: 123, b: 456, c: 789 }

【问题讨论】:

标签: typescript functional-programming fp-ts


【解决方案1】:

使用 TE.Do 当然是一种解决方案(干净且小巧)。 对于另一种用法,您可以使用管道链接您的任务。

export const a = (): TE.TaskEither<ErrorA, A> => {
  return TE.right({ a: 123, b: 456, c: 0 });
}

export const b = (): TE.TaskEither<ErrorB, B> => {
  return TE.right({ c: 789 });
}

export const c =(): TE.TaskEither<ErrorA, A> => {
  return pipe(
    a(),
    TE.chain(a => {
      return pipe(
        b(),
        TE.map(b => {
          return {
            ...a,
            c: b.c,
          }
        }),
      );
    }),
  );
}

【讨论】:

    【解决方案2】:

    我建议在这种情况下使用 Do-Notation。这是一个例子。

    import { pipe } from 'fp-ts/function'
    import * as TE from 'fp-ts/TaskEither'
    
    interface A {
      a: number
      b: number
      c: number
    }
    
    interface B {
      c: number
    }
    
    const a = TE.right<Error, A>({ a: 123, b: 456, c: 0 })
    const b = TE.right<Error, B>({ c: 789 })
    
    const c: TE.TaskEither<Error, A> = pipe(
      TE.Do,
      TE.apS('a', a),
      TE.apS('b', b),
      TE.map(({ a, b }) => ({ ...a, ...b }))
    )
    

    如果错误类型不同,您应该考虑将错误包装在联合类型中。 fp-ts Issue Tracker 中有一个更长的线程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-19
      • 2021-12-04
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2021-07-17
      • 1970-01-01
      相关资源
      最近更新 更多