我还在学习和使用fp-ts,还不能弄明白这一点。
我有一个数组的Either<any, number>[],我想得到一个Either<any, number[]>。
我看过Apply.sequenceT和示例sequenceToOption,它看起来很接近。
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 } ]相反,我需要一个错误或数字数组。
发布于 2019-09-15 10:51:40
要从Array<Either<L, A>>转到Either<L, Array<A>>,可以使用sequence
import { array } from 'fp-ts/lib/Array'
import { either } from 'fp-ts/lib/Either'
array.sequence(either)(arrayOfEithers)您的示例还可以使用traverse进一步简化
array.traverse(either)(['1','2','3'], NumberFromString.decode)发布于 2020-10-15 08:50:10
如果您已经在使用io-ts,我建议您将数组添加到解码器中,如下所示:
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> }否则,来自Giovanni的答案应该是好的。
https://stackoverflow.com/questions/57916714
复制相似问题