Most convenient way to write a loop with fixed length and no need for the index?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 30 01:08:42 PDT 2017


On 06/30/2017 12:44 AM, Martin Tschierschke wrote:
> What do I have to do, to make this work?
>
> iota(number).each!...command_x(a...);command_y(b...);command_z(c..))
>                  ^^^^^?
> how to write the lambda?
>
> Similar to the ruby (1..number).each{ commands...}
>
> Don't want to write the following, because the index i is not used
> inside the loop
> and this should be clear when reading it:
>
>   for (i=0;i<number;i++){commands...}
>
> or
>
>   foreach(i;iota(number)){commands...}
>
> Or is there something like number.times!{....} possible?

Seems easy to put together: :)

import std.stdio;

auto times(alias Func, T)(T number) {
     import std.range : iota;
     import std.algorithm : each;
     return number.iota.each!(_ => Func());
}

void foo() {
     writeln("foo");
}

void bar() {
     writeln("bar");
}

void main() {
     3.times!({ foo(); bar(); });
}

Ali



More information about the Digitalmars-d-learn mailing list