Last active
October 19, 2024 03:37
-
-
Save schveiguy/b6b037bdfe74997743de81f8d3f4b92b to your computer and use it in GitHub Desktop.
Possible way to capture things in a loop?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
auto stackFrame(T)(T rng) | |
{ | |
static struct Apply | |
{ | |
import std.range; | |
T rng; | |
int opApply(scope int delegate(ElementType!T) dg) { | |
foreach(e; rng) { | |
if(auto r = dg(e)) | |
return r; | |
} | |
return 0; | |
} | |
} | |
return Apply(rng); | |
} | |
void main() | |
{ | |
import std.stdio; | |
void delegate()[] dgs; | |
foreach(i; [1, 2, 3, 4]) { | |
dgs ~= () => writeln(i); | |
} | |
foreach(d; dgs) d(); // 4 4 4 4 | |
dgs = null; | |
foreach(i; [1, 2, 3, 4].stackFrame) { | |
dgs ~= () => writeln(i); | |
} | |
foreach(d; dgs) d(); // 1 2 3 4 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment