5

I have a list of strings, string[]

I map a validate function that returns Either<Error, string>[]

I want [Error[], string[]], all validation errors and all validated strings.

Can sequence(Either.Applicative) or traverse(Either.Applicative) return all errors encountered? I only received Either<Error, string[]>, just the first error returned. Would I need to write my own Applicative, something with a Semigroup that merges lefts and rights?

I was able get all Errors by changing map to reduce with a fold.

I also thought of reversing the validation eithers, and running it twice. One function returns the valid strings, one returns the errors.

steve76
  • 302
  • 2
  • 9

1 Answers1

6

traverse returns an Either, but you want to accumulate both Lefts and Rights. You can map over the inputs and then separate the elements.

import * as A from 'fp-ts/lib/Array';
import * as E from 'fp-ts/lib/Either';
import { pipe } from 'fp-ts/lib/function';

declare const input: string[];
declare function validate(input: string): E.Either<Error, string>;

const result = pipe(input, A.map(validate), A.separate);
// result.left: Error[]
// result.right: string[]
Denis Frezzato
  • 957
  • 6
  • 15