traverseList<E, A, B> function

Either<E, ImmutableList<B>> traverseList<E, A, B>(
  1. Either<E, B> f(
    1. A
    ),
  2. ImmutableList<A> list
)

Processes each item of an ImmutableList through a function f that returns an Either, and collects the results into a new ImmutableList.

This function goes through each item of the provided list and applies the function f to it. If at any point the function f returns a Left, the traversal is stopped, and that Left value is returned immediately. If all items are successfully processed, their results are collected into an ImmutableList wrapped in a Right.

Parameters:

  • f: A function that takes an item of type A and returns an Either of type E or B.
  • list: An ImmutableList of items of type A to be processed.

Returns:

An Either containing an ImmutableList of the processed items. Returns the first Left encountered while processing the input list.

Examples:

var myList = il.ImmutableList<int>([1, 2, 3]);
var result = traverseList((int item) => item > 1 ? Right(item) : Left("Error"), myList);
print(result); // Outputs: Left("Error")
var myListWithoutError = il.ImmutableList<int>([2, 3, 4]);
var successfulResult = traverseList((int item) => Right(item * 2), myListWithoutError);
print(successfulResult); // Outputs: Right(ImmutableList([4, 6, 8]))

Implementation

Either<E, il.ImmutableList<B>> traverseList<E, A, B>(
    Either<E, B> Function(A) f, il.ImmutableList<A> list) {
  final results = <B>[];

  for (final item in list) {
    final result = f(item);
    switch (result) {
      case Left(value: var leftValue):
        return Left<E, il.ImmutableList<B>>(leftValue);
      case Right(value: var rightValue):
        results.add(rightValue);
    }
  }

  return Right(il.of(results));
}