From: Stefan Bellon on
On Fri, 20 Jun, Reinert Korsnes wrote:

> -- I want something more beautiful than this loop:
>
> for k in 1 .. Positive(X.Length) loop
> do_something(X.Element(k));
> end loop;

Sorry to high-jack this thread, but I'd like to comment on a somewhat
related topic: For a very long time I was looking for some way to
return a range from a function so that you can do something elegant
like in the following:

for I in Get_Range loop
Do_Something (I);
end loop;

I always thought it to be a deficiency of Ada not being able to return
a range from a function.

A few weeks ago I realised the following solution, which I'd like to
share:

generic
type Index_Type is (<>);
package Generic_Range_Objects is

type Empty_Component is null record;
for Empty_Component'Size use 0;

type Range_Type is array (Index_Type range <>) of Empty_Component;
pragma Pack (Range_Type);

end Generic_Range_Objects;

And an instance for Integer ranges ...

with Generic_Range_Objects;

package Integer_Range_Objects is new Generic_Range_Objects (Integer);

Now you can do the following:

function Get_Range
return Integer_Range_Objects.Range_Type
is
begin
return (42 .. 128 => <>);
end Get_Range;

And then:

for I in Get_Range'Range loop
Do_Something (I);
end loop;

It's not as elegant as I wished (because of the additional 'Range), but
it is simple and light-weight enough to be usable.

--
Stefan Bellon