简体   繁体   中英

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.

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)

If you are already using io-ts I would recommend adding your array to the decoder like so:

import { NumberFromString } from 'io-ts-types/lib/NumberFromString'
import * as t from 'io-ts'

const { decode } = t.array(NumberFromString)

const resultA = decode(['1','2','3']);
const resultB = decode(['1','2','junk']);

console.log(resultA) // { _tag: 'Right', right: [1, 2, 3] }
console.log(resultB) // { _tag: 'Left', left: <ERRORS> }

Otherwise the answer from Giovanni should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM