[Issue 4085] Steps toward a static foreach

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Jul 25 04:20:06 PDT 2013


http://d.puremagic.com/issues/show_bug.cgi?id=4085


monarchdodra at gmail.com changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |monarchdodra at gmail.com


--- Comment #4 from monarchdodra at gmail.com 2013-07-25 04:20:03 PDT ---
(In reply to comment #3)
> *** Issue 10712 has been marked as a duplicate of this issue. ***

Copy pasting a proposed implementation from 10712. Pretty much the same thing,
but also handles indiscriminate types. It passes the prior tests, as well as
handles the useage with doubles, or chars:

//--------
template Iota(alias h)
{
    alias Iota = IotaImpl!(0, h, 1);
}
template Iota(alias l, alias h)
{
    alias Iota = IotaImpl!(l, h, 1);
}
template Iota(alias l, alias h, alias inc)
{
    alias Iota = IotaImpl!(l, h, inc);
}

template IotaImpl(alias l, alias h, alias inc, T...)
{
    alias E = CommonType!(l, h, inc);
    static if (inc == 0)
        static assert(0, "increment must be non-0");
    else static if (inc > 0 && l >= h)
        alias IotaImpl = T;
    else static if(inc < 0 && l <= h)
        alias IotaImpl = T;
    else
        alias IotaImpl = IotaImpl!(cast(E)(l + inc), h, inc, T, cast(E)l);
}
//--------

//--------
    foreach(idx; Iota!(0, 0))
    write(idx, ' '); // prints 
    writeln();

    foreach(idx; Iota!(0, 10))
    write(idx, ' '); // prints 0, 1, ..., 9
    writeln();

    foreach(idx; Iota!(2, 10))
    write(idx, ' '); // prints 2, 3, ..., 9
    writeln();

    foreach(idx; Iota!(0, -10, -1))
    write(idx, ' '); // prints 0, -1, ..., -9
    writeln();

    foreach_reverse(idx; Iota!(-9, 1))
    write(idx, ' '); // prints 0, -1, ..., -9
    writeln();

    foreach(idx; Iota!(0.5, 10))
    write(idx, ' '); // prints 0.5, 1.5, ..., 9.5
    writeln();

    foreach(idx; Iota!(0, 1, 0.1))
    write(idx, ' '); // prints 0 0.1 ... 0.9
    writeln();

    foreach(idx; Iota!('a', cast(char)('z' + 1), cast(char)1))
    write(idx, ' '); // prints a b ... z
    writeln();
//--------

Maybe it's time to submit this to phobos?

This belongs in typecons?

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list