3

我有一个字符串列表,string[]

我映射了一个返回的验证函数Either<Error, string>[]

我想要[Error[], string[]],所有验证错误和所有验证字符串。

可以sequence(Either.Applicative)traverse(Either.Applicative)返回所有遇到的错误吗?我只收到了Either<Error, string[]>,只是返回了第一个错误。我是否需要编写我自己的 Applicative,一个包含左右合并的 Semigroup 的东西?

我可以通过更改map为.reducefold

我还想过反转验证,然后运行两次。一个函数返回有效字符串,一个函数返回错误。

4

1 回答 1

4

traverse返回 an Either,但您想同时累积Lefts 和Rights。您可以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[]
于 2020-08-04T09:40:17.873 回答