如何在 FP-TS 中展平 TaskEither<Error, Either<Error, T>>

How to flatten TaskEither<Error, Either<Error, T>> in FP-TS

我是 fp-ts 的新手。在处理 Either、IO 和 ... 的组合时,我习惯于理解 scala 问题是,假设我们有带签名的函数

either(T): Either<Error, T>
ioEither(T): IOEither<Error, T>
taskEither(T): TaskEither<Error, T>
...

我想把它们结合起来,我得到了一些类似

的东西
pipe(T, taskEither, map(either)): TaskEither<Error, Either<Error, T>>

应该压平。

如何组合类型函数T -> M<T>,其中 M 是 IO 或 Task,T -> M<Error, T> 其中 M 是 Either、TaskEither 或 IOEither,在过程中扁平化,就像使用 scala 进行理解一样?

解决此问题的一种方法是简单地选择 TaskEither 作为您选择的 monad,然后将其他所有内容提升到其中。

import { pipe } from 'fp-ts/function'
import { Either } from 'fp-ts/Either'
import { IOEither } from 'fp-ts/IOEither'
import { TaskEither, fromEither, fromIOEither, chain } from 'fp-ts/TaskEither'

declare const either: <T>(t: T) => Either<Error, T>
declare const ioEither: <T>(t: T) => IOEither<Error, T>
declare const taskEither: <T>(t: T) => TaskEither<Error, T>

const liftedIOEither = <T>(t: T) => fromIOEither(ioEither(t))
const liftedEither = <T>(t: T) => fromEither(either(t))

const res = pipe(
  1,
  liftedEither,
  chain(liftedIOEither),
  chain(taskEither),
) // TaskEither<Error, number>