# Compiled function without MainEvaluate

My question is related to this thread here:

Compiling more functions that don't call MainEvaluate

Within the thread it is suggested to use pure functions and then the option "InlineExternalDefinitions" to avoid calls of MainEvalute.

But how can one avoid MainEvalute if one wants to call a function in the iteration limits of a table within Compile[]. E.g. something like

g = #^2 &;
f = # + 1 &;

compiledFunction =
Compile[{{x, _Real, 0}}, Table[g[x], {n, f, 2}],
CompilationOptions -> {"InlineExternalDefinitions" -> True}];

CompilePrint[compiledFunction]


returns

        1 argument
11 Integer registers
4 Real registers
1 Tensor register
Underflow checking off
Overflow checking off
Integer overflow checking on
RuntimeAttributes -> {}

R0 = A1
I6 = 0
I2 = 2
I7 = -1
I0 = 1
Result = T(R1)0

1   I3 = MainEvaluate[ Hold[f][ I0]]
2   I4 = IteratorCountI[ I3, I2]]
3   I5 = I6
4   I8 = Subtract[ I4, I7]
5   T(R1)0 = Table[ I8]
6   I9 = I7
7   goto 12
8   I10 = I3 + I9
9   R1 = R0
10  R3 = Square[ R1]
11  Element[ T(R1)0, I5] = R3
12  if[ ++ I9 <= I4] goto 8
13  Return


and calls MainEvaluate. Is it possible to call externally defined functions within the Compile environment to use them as upper or lower boundary of an iteration within Table[] without calling MainEvaluate?

In your case, you can use

With[{f = f, g = g},
fc1 = Compile[{{x, _Real, 0}}, Table[g[x], {n, f, 2}]];
]


or

Function[{f, g},
fc2 = Compile[{{x, _Real, 0}}, Table[g[x], {n, f, 2}]]
][f, g]


• @DisplayName In some cases you may also call Evaluate on the body of the compileable function, i.e. Compile[{{x, _Real, 0}}, Evaluate[Table[g[x], {n, f, 2}]]] In your toy example this would result in Compile[{{x, _Real, 0}}, {x^2}] – LLlAMnYP Feb 12 '18 at 13:54