gcanti / fp-ts

Functional programming in TypeScript
https://gcanti.github.io/fp-ts/
MIT License
10.82k stars 502 forks source link

How to convert TaskEither<E, R>[] into TaskEither<E[], R[]> #1174

Closed VassilisPallas closed 4 years ago

VassilisPallas commented 4 years ago

I have a pipe that returns TaskEither<E, R>[] but what I need is to convert this to TaskEither<E[], R[]>.

I tried to convert the TaskEither to Task<Either<E, R>[]> and a merge function by making a validation monoid, and using foldMap to map this monoid.

A.array.sequence(T.task),
T.map(
  E.foldMap(
    E.getValidationMonoid(A.getMonoid<E>(), A.getMonoid<R>())
  )(
    E.bimap(
      (left: E) => [left],
      (data: R) => [data],
    ),
  ),
),

but it returns this error: '<E>(fa: Either<E, Either<E, R>>) => Either<E[], R[]>' is not assignable to parameter of type '(a: Either<E, R>[]) => Either<E[], R[]>'.

What am I missing here?

gcanti commented 4 years ago

How to convert TaskEither<E, R>[] into TaskEither<E[], R[]>

The anwser is always traverse

import * as A from 'fp-ts/lib/Array'
import { array } from 'fp-ts/lib/Array'
import * as TE from 'fp-ts/lib/TaskEither'

declare const xs: TE.TaskEither<Error, number>[]

// result: TE.TaskEither<Error[], number[]>
const result = array.traverse(TE.getTaskValidation(A.getMonoid<Error>()))(xs, TE.mapLeft(A.of))