Long time ago I wrote a macro, which expands global DownValues
- based definitions, called withGlobalFunctions
. It can be found at the end of this post. With it, all you need to do is wrap the Compile
call like this:
g[x] := x^3;
f[x] := x^2 + g[x];
cf = withGlobalFunctions @ Compile[{{x, _Real}}, f[x]]
This has the advantage over Evaluate
advice in that you can't leak a global value for x
in, even if it exists. And it has an advantage over "InlineExternalDefinitions" -> True
advice in that it expands arbitrary long chains of calls.
The limitation of this approach is that patterns in function definitions you may want to inline / expand in this way, better be very simple, involving blanks but not much else. This is because what this does is a kind of a macro-expansion, without actual evaluation involved. So that expansion will get stuck if patterns do any non-trivial checks.
withGlobalFunctions
can trivially be extended to expand definitions based on other ...Values
. As written, it only expands definitions from Global`
context, but that restriction can be removed or lifted as well.
Compile[{{x, _Real}}, Evaluate[x^2 + g[x]]]
$\endgroup$ – QuantumDot Mar 13 '20 at 17:30g[x_] := x^3; cf = Compile[{{x, _Real}}, x^2 + g[x]]
, although it and @ilian's suggestion both containMainEvaluate[]
. Note the argument tog
is a patternx_
, not a symbolx
. $\endgroup$ – Michael E2 Mar 13 '20 at 21:45Block[{x}, ...]
aroundCompile
. But even then, I think it is generally an error - prone practice, unless you are in full control of exact evaluation path for the stuff insideEvaluate
. $\endgroup$ – Leonid Shifrin Mar 13 '20 at 23:09Block[{x}, With[{code = x^2 + g[x]}, Compile[{{x, _Real}}, code]]]
. $\endgroup$ – Henrik Schumacher Mar 14 '20 at 7:44