0

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

基本上,我想要一个 Either<List,R>,而不是 map5 的 Either<L,R> 结果。

有没有一种开箱即用的方式来做到这一点 dartz ?

4

1 回答 1

0

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

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 函数并将左侧从最终结果映射到一个空列表,以匹配预期的返回类型,如我已经知道它不是左撇子。

于 2021-10-26T10:29:09.253 回答