sequenceList<A> function

Option<ImmutableList<A>> sequenceList<A>(
  1. ImmutableList<Option<A>> list
)

Takes an ImmutableList of Option values and returns an Option containing an ImmutableList of values.

If any of the Option values in the input list 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:

  • list: An ImmutableList of Option values.

Returns:

An Option containing an ImmutableList of the values from the input list. Returns None if any of the input values is None.

Examples:

var listOfOptions = il.ImmutableList<Option<int>>([
  Some(1),
  Some(2),
  Some(3)
]);
var result = sequenceList(listOfOptions);
print(result); // Outputs: Some(ImmutableList([1, 2, 3]))
var listOfOptionsWithNone = il.ImmutableList<Option<int>>([
  Some(1),
  None(),
  Some(3)
]);
var resultWithNone = sequenceList(listOfOptionsWithNone);
print(resultWithNone); // Outputs: None

Implementation

Option<il.ImmutableList<A>> sequenceList<A>(il.ImmutableList<Option<A>> list) {
  final results = <A>[];

  for (var opt in list) {
    switch (opt) {
      case Some(value: var someValue):
        results.add(someValue);
        break;
      case None():
        return None();
    }
  }

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