foreach without front
Ali Çehreli via Digitalmars-d
digitalmars-d at puremagic.com
Thu Aug 14 10:39:48 PDT 2014
On 08/11/2014 08:40 AM, Jonathan Marler wrote:
> I know this is kinda "nit picky" but it would be nice if foreach
> supported iterating through input ranges without accessing the front
> function.
>
> foreach(myInputRange) {
> // myInputRange has a front function but it is
> // never called because the foreach has no type list
> }
The syntax does not allow that but I have discovered a WAT! :) If you
implement iteration by opApply() member functions, it is possible to use
any random name and it works.
The following type provides both an int and a void overload.
import std.stdio;
struct S
{
int opApply(int delegate(int) dg)
{
foreach (i; 0 .. 3) {
int b = dg(i);
if (b) {
return b;
}
}
return 0;
}
int opApply(int delegate() dg)
{
foreach (_; 0 .. 3) {
int b = dg();
if (b) {
return b;
}
}
return 0;
}
}
void main()
{
auto s = S();
foreach (i; s) {
writeln(i);
}
// Replace WAT with any other random name and it still works.
// foreach (_; s) would make the most sense.
foreach (WAT; s) {
writeln("_");
}
}
Ali
More information about the Digitalmars-d
mailing list