traverseList<A, B> function
- Option<
B> fn(- A
Takes an ImmutableList
and a function, then applies the function to each item in the list.
This function maps each element of the input list to an Option
using the provided function fn
.
If the result of applying fn
to any element is None
, this function returns None
.
Otherwise, it collects all the values inside the Some
variants into an ImmutableList
and wraps it in a Some
.
Parameters:
fn
: A function that takes a value of typeA
and returns anOption
of typeB
.
Returns:
A curried function that takes an ImmutableList
of values of type A
and returns
an Option
containing an ImmutableList
of the mapped values of type B
.
Returns None
if the result of mapping any input value is None
.
Examples:
var listOfInts = il.ImmutableList<int>([1, 2, 3]);
Option<int> addOne(int x) => Some(x + 1);
var traverseFn = traverseList(addOne);
var result = traverseFn(listOfInts);
print(result); // Outputs: Some(ImmutableList([2, 3, 4]))
Option<int> returnNoneForThree(int x) => x == 3 ? None() : Some(x);
var traverseFnWithNone = traverseList(returnNoneForThree);
var resultWithNone = traverseFnWithNone(listOfInts);
print(resultWithNone); // Outputs: None
Implementation
Option<il.ImmutableList<B>> Function(il.ImmutableList<A>) traverseList<A, B>(
Option<B> Function(A) fn) {
Option<il.ImmutableList<B>> foldFn(Option<il.ImmutableList<B>> acc, A item) {
return match<il.ImmutableList<B>, Option<il.ImmutableList<B>>>(
() => None<il.ImmutableList<B>>(), (il.ImmutableList<B> accList) {
Option<B> resultOption = fn(item);
return match<B, Option<il.ImmutableList<B>>>(
() => None<il.ImmutableList<B>>(),
(B value) => Some(il.append(value)(accList)))(resultOption);
})(acc);
}
return il.foldLeft<A, Option<il.ImmutableList<B>>>(
Some(il.ImmutableList<B>([])))(foldFn);
}