loopsada

How to iterate over a range with a custom step?


How can I iterate over a range in Ada with a custom step ?

For I in Integer'Range
loop
    -- do something every 10 steps
end loop;

Can I define a subtype with specific step ?


Solution

  • Typically one does an explicit increment:

    declare
       I : T := Start;
    begin
       loop
          exit when I > Stop;
    
          -- do something every Step steps
          I := I + Step;
       end loop;
    end;
    

    Sometimes you need a slightly different test:

    declare
       I : T := Start;
    begin
       loop
          -- do something every Step steps
    
          exit when I > Stop - Step;
    
          I := I + Step;
       end loop;
    end;
    

    when that last increment will overflow. Or you can handle the exception.