I thought of this when someone asked the age-old question about closures not capturing loop variables.
https://gist.github.com/schveiguy/b6b037bdfe74997743de81f8d3f4b92b
How does it work? It works because opApply is passed a lambda function generated by the compiler to implement the foreach body.
But because this is a separate function, when you close over that lambda, the lambda's stack is independently allocated on the heap for each loop iteration.
This doesn't exactly capture all variables, any variables in the enclosing scope are not duplicated (so it doesn't in effect capture what values were outside the loop body at that point in time). But isn't this the point?
In any case, thought it was interesting, and wondering if anyone's every thought of this before.
There are some lifetime and quality of life issues, but it's somewhat similar to std.parallelism
in hooking opApply for nifty gain.
-Steve