Search code examples
flutterdartfunctional-programmingdartz

How to "concatenate" Lefts using Dartz


I want to do something similar to a Either.map5 on several Either types. But, instead of keeping just the first Left in case of my Eithers being Left, I want to keep all the Left Either contents, and put them into a List.

Basically instead of the Either<L,R> result of map5 I would like to have a Either<List,R>.

Is there a out-of-the-box way of doing this with dartz ?


Solution

  • I've created my own solution to my needs, here it is:

    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());
      }
     }
    }
    

    Basically, if any of the provided Eithers is a Left I return a left with the list of Left contents, otherwise I call the bundled map5 function and map the left from the final result to an empty list just to match the expected return type, as I already know it is not a left anyways.