comp.lang.ada
 help / color / mirror / Atom feed
From: Stefan Bellon <bellon@software-erosion.org>
Subject: Returning ranges from a function (was: How to loop (elegant) throug a vector ?)
Date: Fri, 20 Jun 2008 19:12:37 +0200
Date: 2008-06-20T19:12:37+02:00	[thread overview]
Message-ID: <20080620191237.5971480b@cube.tz.axivion.com> (raw)
In-Reply-To: aMednZL3l638M8bV4p2dnAA@telenor.com

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




  parent reply	other threads:[~2008-06-20 17:12 UTC|newest]

Thread overview: 15+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2008-06-20 13:19 How to loop (elegant) throug a vector ? Reinert Korsnes
2008-06-20 14:49 ` Pascal Obry
2008-06-20 17:12 ` Stefan Bellon [this message]
2008-06-22 14:01   ` Returning ranges from a function (was: How to loop (elegant) throug a vector ?) Maciej Sobczak
2008-06-22 18:47     ` Stefan Bellon
2008-06-22 21:06       ` Maciej Sobczak
2008-06-23  9:47         ` Stefan Bellon
2008-06-23 12:06           ` Maciej Sobczak
2008-06-23 12:28             ` christoph.grein
2008-06-20 19:21 ` How to loop (elegant) throug a vector ? Jeffrey R. Carter
2008-06-20 19:48   ` Reinert Korsnes
2008-06-20 23:25     ` Jeffrey R. Carter
2008-06-23 17:14     ` Matthew Heaney
2008-06-23 17:11   ` Matthew Heaney
2008-06-23 17:08 ` Matthew Heaney
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox