does D already have too many language features ?

bauss jj_1337 at live.dk
Tue Apr 9 12:19:20 UTC 2019


On Tuesday, 9 April 2019 at 09:45:15 UTC, Jacob Carlborg wrote:
> On 2019-04-08 22:42, jmh530 wrote:
>
>> Numeric range literals are a nice feature in Matlab and some 
>> other languages for some tasks.
>
> Yeah, I like it too. But 1..10 could be a generic range type 
> that can be used everywhere and the foreach statement would 
> need a specialized syntax.

Yep could be similar to Python's range.

import std.stdio;

struct RangeImpl(T)
{
     T from;
     T to;
     bool reversed;

     @property bool empty()
     {
         return reversed ? from == to : from >= to;
     }

     T front()
     {
         return from;
     }

     void popFront()
     {
         if (reversed)
         {
             from--;
         }
         else
         {
             from++;
         }
     }
}

auto range(T)(T from, T to)
{
     return RangeImpl!T(from, to, from > to);
}

void main()
{
     foreach (i; range(0, 10))
     {
         writeln(i);
     }

     // Same as foreach_reverse
     foreach (i; range(10, 0))
     {
         writeln(i);
     }
}

Output:
0
1
2
3
4
5
6
7
8
9
10
9
8
7
6
5
4
3
2
1


More information about the Digitalmars-d mailing list