Futures advent day 16

Day 16 - Iterating Over a List

Yesterday we looked at the repeat utility, and how it can form a future representing a repeated sequence of attempts to perform some action, when each attempt returns a future to represent it. That example used the result of each attempt to decide if the overall operation should be considered a success, or to have another go.

Sometimes, the number of times to run a loop is known in advance, or at least does not depend on the result, because we wish instead to iterate over items of some given input data. To perform this we can use repeat like a perl foreach {} loop, taking a list of items from an array reference, and invoking the action block once for each item in the list. As before, it returns a future which this time will complete once the input list is exhausted and the final item's attempt has completed.

my %items = ...;

my $f = repeat {
  my ( $key ) = @_;
} foreach => [ keys %items ];


Because a foreach list is provided, the repeat function passes the body code successive values from it on each iteration. We don't need to supply a while or until condition here, because the loop knows to terminate when the list is exhausted.

<< First | < Prev | Next >

No comments:

Post a Comment