foreach

Rikki Cattermole via Digitalmars-d digitalmars-d at puremagic.com
Fri Jun 13 05:17:34 PDT 2014


On 13/06/2014 3:00 a.m., Manu via Digitalmars-d wrote:
> I often find myself wanting to write this:
>    foreach(; 0..n) {}
> In the case that I just want to do something n times and I don't
> actually care about the loop counter, but this doesn't compile.
>
> You can do this:
>    for(;;) {}
>
> If 'for' lets you omit any of the loop terms, surely it makes sense
> that foreach would allow you to omit the first term as well?
> I see no need to declare a superfluous loop counter when it is unused.

Of course my reaction is a library solution:

import std.stdio;
import std.traits;

void times(size_t n, void delegate() c) {
	for (size_t i = 0; i < n; i++)
		c();
}

void times(size_t n, void delegate(size_t) c) {
	for (size_t i = 0; i < n; i++)
		c(i);
}

void iterate(T, U = typeof((T.init)[0]))(T t, void delegate(U) c) {
	foreach(v; t)
		c(v);
}

void iterate(T, U = typeof((T.init)[0]))(T t, void delegate(U, size_t) c) {
	foreach(i, v; t)
		c(v, i);
}

void main() {
	4.times({
		writeln("hi");
	});
	
	4.times((i) {
		writeln("hello ", i);
	});
	
	[1, 2, 3].iterate((uint c) {
		writeln("letter: ", c);
	});
	
	[1, 2, 3].iterate((uint c, i) {
		writeln("letter: ", c, ", at: ", i);
	});
}

But not really what you're wanting I'd imagine.


More information about the Digitalmars-d mailing list