Overview of Ada 2022
Jeff Cousins
Contents   Index   Search   Previous   Next 

4.6 Iterator filters

When iterating through a container, it is often required to filter the results to only return those values that meet some condition. Iterator filters (AI12-0250) adds filters to Ada 2022 to meet this need (see RM 5.5). This feature makes use of the keyword when, for example:
S : constant Set := (for E of C when E mod 2 = 1 => E);
to obtain all the odd elements of Container C.
While most useful in aggregate iterator associations, filters can be used anywhere an iterator is allowed in Ada, including quantified expressions, reduction expressions (see 2.5), and even loop statements. Similarly, iterator filters can be used with any kind of iterator, including the traditional discrete iterator. So a simple for loop like:
for I in 1 .. 100 loop
   if I mod 2 = 0 then
       -- Only process even values.
       ...
   end if;
end loop;
could instead be written as:
for I in 1 .. 100 when I mod 2 = 0 loop
   -- Only process even values.
   ...
end loop;

Contents   Index   Search   Previous   Next 
© 2021, 2022 Jeff Cousins