【问题标题】:How to "concatenate" Lefts using Dartz如何使用 Dartz“连接”Left
【发布时间】:2021-12-11 08:28:46
【问题描述】:

我想在几个 Either 类型上做类似于 Either.map5 的事情。 但是,我不想只保留第一个 Left 以防我的 Eithers 被留下,而是想保留所有 Left Either 的内容,并将它们放入一个列表中。

基本上,而不是 map5 的 Either 结果,我想要一个 Either

是否有一种开箱即用的方式来使用 dartz 执行此操作?

【问题讨论】:

  • 我不知道 dartz 但如果你想积累Lefts 你需要另一种类型,因为Either 通常包含错误处理。您要查找的类型通常称为Validation 或类似名称。
  • 是的,这也是我从 Arrow-kt 知道的类型,但我在 dartz 中找不到类似的类型。话虽如此,我提出了一个厚颜无耻的解决方案。检查我自己的答案。

标签: flutter dart functional-programming dartz


【解决方案1】:

我已经根据自己的需要创建了自己的解决方案,这里是:

class EitherExtensions {

static Either<List<L>, F> map5AppendingLefts<L, A, A2 extends A, B,
      B2 extends B, C, C2 extends C, D, D2 extends D, E, E2 extends E,F>(
  Either<L, A2> fa,
  Either<L, B2> fb,
  Either<L, C2> fc,
  Either<L, D2> fd,
  Either<L, E2> fe,
  F fun(A a, B b, C c, D d, E e)) {

  IList<Either<L, Object?>> listOfEithers = IList.from([fa, fb, fc, fd, fe]);
  List<L> listOfLefts = List<L>.empty(growable: true);

  if (listOfEithers.any((either) => either.isLeft())) {
  listOfEithers
      .forEach((element) => {element.leftMap((l) => 
  listOfLefts.add(l))});

  return Left(listOfLefts);

} else {
  return Either.map5(fa, fb, fc, fd, fe,
          (A a, B b, C c, D d, E e) => fun(a, b, c, d, e))
         .leftMap((l) => List<L>.empty());
  }
 }
}

基本上,如果任何提供的 Eithers 是 Left,我将返回一个带有 Left 内容列表的 left,否则我调用捆绑的 map5 函数并将左侧从最终结果映射到一个空列表,以匹配预期的返回类型,因为我已经知道它不是左。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    相关资源
    最近更新 更多