Skip to main content

recursion - Compile recursive function modifying global variables


How to compile recursive formula when it relies on more than a few global variables (global to the topmost compiled function)? It is unreasonable to pass on all such variables to each recursive subroutine (there are more than one), as:



  • that would require a lot of tensor copying which would cause a slowdown;

  • even if passing globals would be possible, returning all affected globals from each subroutine would be tedious as each function must return a regular tensor of uniform data type.


Consider the following toy problem to calculate the factorial:



fact[x_] := Module[{sub, global = 1},
sub[y_] := If[y > 0, global = global*y; sub[y - 1]];
sub@x;
global];

How to compile it without passing global to sub? While this code works nicely in the general Mathematica interface, the following compiled version will call MainEvaluate as there is a SetDelayed expression which the compiler cannot handle:


factC = Compile[{{x, _Integer}}, Module[{global = 1, sub},
sub[y_] := If[y > 0, global = global*y; sub[y - 1]];
sub@x;
global]];


Is there any way to overcome this problem?




Comments