First class lazy Interval

bearophile bearophileHUGS at lycos.com
Fri Feb 27 01:43:46 PST 2009


D2 supports the interval syntax in the foreach:
foreach (i; 1..1000) {...}

Such intervals are useful in a very large number of situations. So, with the new Range support, it may be useful to allow the interval syntax to be used in other contexts as well.
So x..y may become a first-class lazy interval from x to y-1, that can be passed to functions too, etc, and not just used into foreach (the compiler can recognize it, and often optimize it away in many situations, replacing it with a normal for() loop).

Optional possibilities:

1) x..y..s
where s is a step/stride, so you can define odd numbers, etc.
1..10..3 ==> 1 4 7
10..1..-2 ==> 10 8 6 4 2
1..5..1 ==> 1 2 3 4
I don't like this syntax much, but I think it's acceptable.

2) Such intervals may enjoy a fast opIn_r() method, for quick membership test:
if (a in 0..10) {...}
if (c in 'c'..'z'+1) {...} 
(Notice the +1 because all intervals are open on the right).
For the compiler that's syntax sugar of (a>0 && a<10).
For the user I think it's easy to remember such syntax.

Originally I have thought about the syntaxes [x..y] and [x..y..s] as eager, that is arrays of the (integer?) numbers of the interval. But they are just sugar for the (future?) function of std.algorithm that produces an array from a lazy iterable, so it may not be useful enough.

Bye,
bearophile



More information about the Digitalmars-d mailing list