DMD range support?

Sergey Gromov snake.scaly at gmail.com
Sat Jan 10 19:17:58 PST 2009


Sat, 10 Jan 2009 13:53:44 -0500, Jarrett Billingsley wrote:

> On Sat, Jan 10, 2009 at 12:36 PM, Sergey Gromov <snake.scaly at gmail.com> wrote:
>> DMD supports ranges in foreach for more than a month, but I still cannot
>> find any docs or at least examples of the range syntax.  Lots of
>> syntaxes were discussed and it's absolutely not obvious which of them
>> actually got into the compiler.
>>
>> Is this page still relevant?
>> http://ssli.ee.washington.edu/~aalexand/d/tmp/std_range.html
>>
> 
> Maybe it just means the ranges in std.range got an opApply, or some
> kind of special treatment by the compiler?

No, the following works:

struct Generator(int start, int step, int end)
{
  private int head_ = start;
  int head() { return head_; }
  void next() { head_ += step; }
  bool empty() { return head_ > end; }
}

import std.stdio;

void main()
{
  Generator!(2, 7, 50) gen;
  foreach (i; gen)
    writefln(i);
}

so at least the test method is empty(), not done().  That's a relief.
OTOH it does not work if the head is an actual field:

struct Generator(int start, int step, int end)
{
  int head = start;
  void next() { head += step; }
  bool empty() { return head > end; }
}

If you use it with foreach (i; gen) you get

  Error: cannot infer type for i
  
and for foreach (int i; gen):

  Error: no property 'opApply' for type 'Generator!(2,7,50)'
  Error: function expected before (), not 1 of type int



More information about the Digitalmars-d mailing list