On Thursday, 20 June 2019 at 20:38:48 UTC, Dennis wrote:
On Thursday, 20 June 2019 at 19:09:11 UTC, Emmanuelle wrote:
Is there any trait or Phobos function for transforming a
function/delegate/lambda/whatever's body into a string
suitable for `mixin(...)`? For example:
See:
https://forum.dlang.org/post/kozwskltzidfnatbp...@forum.dlang.org
If not, is there any way to do this _without_ using strings?
Depends on what you are trying to achieve with mixing in
function body code. If you just want to execute the function
code, you can just call it (obviously), so I assume you want
dynamic scoping (that global variables are overridden by local
variables from the caller) or something?
Yeah, I want to be able to basically use mixin templates but with
expressions instead, with the code being executed on the scope of
the caller, not the callee; but it seems that's impossible
without passing strings. For example, I recently hit an issue
with closure scoping
(https://forum.dlang.org/post/rnxebjcfpmyzptpwz...@forum.dlang.org) that can be worked around by using IIFEs; I thought, hey, maybe I could make a mixin that turns, say, this (taking the example from the post I just linked):
---
((x) => (int i) { nums[x] ~= i; })(x);
---
into this:
---
mixin(capture!(x, (int i) { nums[x] ~= i; });
---
where the variables I need captured go first there (in this case,
only `x`). Of course, that doesn't work unless I use strings
everywhere:
---
mixin(capture!("x", q{(int i) { nums[x] ~= i; }});
---
which I find rather ugly and inconvenient.
The technique you linked seems interesting but also loads of work
so I'll just give up on this idea for now lol. Thanks though!