I want to create a compiled function from inter-dependent code blocks. Here is a minimal example showing the salient features based on strings:
f[x_, g_] := Module[{template, code, block},
block = StringReplace["z = y*#x#;", "#x#" -> ToString[x, InputForm]];
template = "Compile[{}, Module[{y,z}, y = #g#[#x#]; #block# z], CompilationTarget->\"C\"]";
code = StringReplace[template, {"#block#"->block,
"#g#"->ToString[g, InputForm], "#x#"->ToString[x, InputForm]}];
ToExpression[code]
];
Calling f[3, (#^2 &)][]
yields 27
.
Note that
- code block(s) use variables from the template (and other code blocks)
- code block(s) and template use function arguments; actual arguments can be compiled functions themselves
- actual code blocks and template are larger and more complicated
This approach has shortcomings:
StringReplace
does not work recursively, so multiple calls are necessary. Dependencies need to be considered, which can get complicated.- syntax highlighting et al do not work on string literals
- conversions like
ToString[g,InputForm]
seem unnecessary and potentially slow
What would be an approach that avoids these shortcomings?
This question follows up on
Compile from String using function arguments