I am working on a project in which I need to dynamically generate CompiledFunction
s from Inactive
expressions. For example, I might be given something like
expr = Inactivate[Block[{x = ConstantArray[0.0, 100]},
Do[x[[n]] = Sin[n/Pi]*Cos[y + n/100], {n, 100}];
x]];
from which I need to generate the CompiledFunction
given by
Compile[{y}, Block[{x = ConstantArray[0.0, 100]},
Do[x[[n]] = Sin[n/Pi]*Cos[y + n/100], {n, 100}];
x]];
The first thing I tried was simply Compile[{y}, Evaluate@Activate@expr]
, but this is no good; it actually evaluates the Block
prior to compilation, and gives me a CompiledFunction
which computes each array element separately.
For my project, it is crucial that the loop assigning to the array x
be compiled, and I cannot figure out the right combination of Evaluate
, Activate
, Hold
, etc. that will give me what I want. How can I take expr
and generate the CompiledFunction
given above?
P.S. I've noticed that ConstantArray[]
doesn't seem to be compilable. Is there a faster way to declare an empty array in compiled functions?