Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array of Either<E,A> to Either<E,A[]> (sequence function in Scalaz)

I am still learning and playing with fp-ts and can't figure this out.

I have an array of Either<any, number>[] and I would like to get an Either<any, number[]>.

I have looked at Apply.sequenceT and the example sequenceToOption and it looks close.

import { NumberFromString } from 'io-ts-types/lib/NumberFromString'
import { Either } from 'fp-ts/lib/Either'

const a:Either<any,number>[] = ['1','2','3'].map(NumberFromString.decode)

console.log(a)
// [ { _tag: 'Right', right: 1 },
//   { _tag: 'Right', right: 2 },
//   { _tag: 'Right', right: 3 } ]

I want instead either an error or array of numbers.

like image 952
anotherhale Avatar asked Sep 13 '19 02:09

anotherhale


1 Answers

To go from Array<Either<L, A>> to Either<L, Array<A>> you can use sequence:

import { array } from 'fp-ts/lib/Array'
import { either } from 'fp-ts/lib/Either'

array.sequence(either)(arrayOfEithers)

Your example can also be further simplified using traverse

array.traverse(either)(['1','2','3'], NumberFromString.decode)
like image 120
Giovanni Gonzaga Avatar answered Oct 17 '22 02:10

Giovanni Gonzaga