I am new to fp-ts. I am used to scala for comprehensions when dealing with combining Either, IO and ... The question is, let's say we have function with signatures
either(T): Either<Error, T>
ioEither(T): IOEither<Error, T>
taskEither(T): TaskEither<Error, T>
...
And I want to combine them, and I get something along the lines of
pipe(T, taskEither, map(either)): TaskEither<Error, Either<Error, T>>
Which should be flattened.
How to combine function of types T -> M<T>
where M is IO or Task, and T -> M<Error, T>
where M is Either, TaskEither or IOEither, flattening in process, like with scala for comprehensions?
CodePudding user response:
One way to go about this is to simply pick TaskEither
as your monad of choice, and lift everything else into it.
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>