Skip to content

Instantly share code, notes, and snippets.

@sinfu
Created October 30, 2010 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinfu/655725 to your computer and use it in GitHub Desktop.
Save sinfu/655725 to your computer and use it in GitHub Desktop.
内部イテレータ
import std.stdio : writeln;
void main()
{
int[] r = [ 1,2,3,4,5,6 ];
writeln("Elements multiplied by 1.5:");
foreach (e; map!"1.5*a"(r.iterator))
{
writeln('\t', e); // 1.5 3 4.5 6 7.5 9
}
writeln("Even elements:");
foreach (e; filter!"!(a % 2)"(r.iterator))
{
writeln('\t', e); // 2 4 6
}
writeln("Elements after the first occurrence of 3:");
foreach (e; find!"a == 3"(r.iterator))
{
writeln('\t', e); // 3 4 5 6
}
writeln("Restarting a broken iteration:");
{
auto it = map!"a * 10"(r.iterator);
foreach (e; it)
{
if (e > 30) break;
writeln('\t', e); // 10 20 30
}
writeln("\t---");
foreach (e; it)
{
writeln('\t', e); // 40 50 60
}
}
}
auto iterator(E)(E[] iterable)
{
return (scope int delegate(ref E) apply)
{
foreach (i, ref e; iterable)
{
if (auto result = apply(e))
{
iterable = iterable[i .. $];
return result;
}
}
iterable = iterable[$ .. $];
return 0;
};
}
//----------------------------------------------------------------------------//
template map(alias fun)
{
auto map(E)(int delegate(scope int delegate(ref E)) it)
{
return (scope int delegate(ref typeof(fun(Lvalue!E))) apply)
{
foreach (ref e; it)
{
auto q = fun(e);
if (auto result = apply(q))
return result;
}
return 0;
};
}
}
template map(string fun)
{
alias map!(unaryFun!fun) map;
}
template find(alias fun)
{
auto find(E)(int delegate(scope int delegate(ref E)) it)
{
foreach (ref e; it)
{
if (fun(e))
break;
}
return it;
}
}
template find(string fun)
{
alias find!(unaryFun!fun) find;
}
template filter(alias fun)
{
auto filter(E)(int delegate(scope int delegate(ref E)) it)
{
return (scope int delegate(ref E) apply)
{
foreach (ref e; it)
{
if (!fun(e))
continue;
if (auto result = apply(e))
return result;
}
return 0;
};
}
}
template filter(string fun)
{
alias filter!(unaryFun!fun) filter;
}
//----------------------------------------------------------------------------//
template Lvalue(T)
{
static extern T Lvalue;
}
template unaryFun(string expr)
{
auto ref unaryFun(A)(auto ref A a)
{
return mixin(expr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment