我有一个字符串列表,string[]
我映射了一个返回 Either<Error, string>[]
的验证函数
我要 [Error[], string[]]
,所有验证错误和所有验证字符串。
可以 sequence(Either.Applicative)
或 traverse(Either.Applicative)
返回遇到的所有错误?我只收到Either<Error, string[]>
,仅返回第一个错误。我是否需要编写自己的 Applicative,使用合并左和右的半群的东西?
我可以通过更改 map
来获得所有错误至 reduce
与 fold
.
我还考虑过反转验证,并运行两次。一个函数返回有效字符串,一个返回错误。
最佳答案
traverse
返回 Either
,但您想同时累积 Left
s 和 Right
s。您可以 map
在输入上,然后分离元素。
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[]
关于fp-ts 返回从任一 [] 序列的所有左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63182408/