【问题标题】:fp-ts Return all left values from an Either[] sequencefp-ts 从 Either[] 序列中返回所有左值
【发布时间】:2020-07-30 22:41:21
【问题描述】:

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

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

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

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

通过使用foldmap 更改为reduce,我能够得到所有错误。

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

【问题讨论】:

    标签: fp-ts


    【解决方案1】:

    traverse 返回一个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[]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 2020-04-25
      • 1970-01-01
      • 2021-07-17
      • 2020-09-08
      相关资源
      最近更新 更多