4
$\begingroup$

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[1], 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?

$\endgroup$

1 Answer 1

4
$\begingroup$

In your case, you can use

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

or

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

which both lead to a full inclusion of your definitions.

$\endgroup$
2
  • $\begingroup$ Thank you very much :) $\endgroup$
    – NeverMind
    Commented Feb 12, 2018 at 13:00
  • 2
    $\begingroup$ @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[1], 2}]]] In your toy example this would result in Compile[{{x, _Real, 0}}, {x^2}] $\endgroup$
    – LLlAMnYP
    Commented Feb 12, 2018 at 13:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.