traverseList<E, A, B> function
- TaskEither<
E, B> f(- A
- ImmutableList<
A> list
Traverses a list of items, applying a function to each item, and then
sequences the resulting list of TaskEither
into a single TaskEither
that
produces a list of results.
The provided function f
should transform an item of type A
into a TaskEither<E, B>
.
If any of the transformed TaskEither
computations results in a Left
,
the whole computation will short-circuit and return that Left
.
If all computations are successful (i.e., they all result in a Right
),
a single Right
containing a list of all the results is returned.
Example:
final items = il.ImmutableList<int>([1, 2, 3]);
TaskEither<String, int> doublingFunction(int item) =>
TaskEither(() => Future.value(Right<String, int>(item * 2)));
final result = await traverseList(doublingFunction, items);
if (result is Right) {
print(result.value); // Expected output: [2, 4, 6]
}
Error handling example:
final items = il.ImmutableList<int>([1, 2, 3]);
TaskEither<String, int> functionWithError(int item) {
if (item == 2) {
return TaskEither(() => Future.value(Left<String, int>("Error on 2")));
} else {
return TaskEither(() => Future.value(Right<String, int>(item * 2)));
}
}
final result = await traverseList(functionWithError, items);
if (result is Left) {
print(result.value); // Expected output: "Error on 2"
}
@param f The function to be applied to each item in the list.
@param list The list of items to traverse.
@return A Future
that resolves to an Either
containing either an error
or a list of results.
Implementation
Future<e.Either<E, il.ImmutableList<B>>> traverseList<E, A, B>(
TaskEither<E, B> Function(A) f, il.ImmutableList<A> list) async {
final results = <B>[];
for (final item in list) {
final result = await f(item).value();
switch (result) {
case e.Left(value: var leftValue):
return e.Left<E, il.ImmutableList<B>>(leftValue);
case e.Right(value: var rightValue):
results.add(rightValue);
}
}
return e.Right<E, il.ImmutableList<B>>(il.of(results));
}