9

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.

tomaj
  • 1,570
  • 1
  • 18
  • 32
anotherhale
  • 175
  • 1
  • 6

2 Answers2

9

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)
tomaj
  • 1,570
  • 1
  • 18
  • 32
Giovanni Gonzaga
  • 1,185
  • 9
  • 8
0

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.