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]];

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]];

Is there any way to overcome this problem?

István Zachar

Posted 2013-08-26T19:56:46.837

Reputation: 44 135


Related mathgroup post: Pass by reference for compiled functions No solution general enough though.

– ssch – 2013-08-26T21:37:06.477

@ssch This pretty much tells me that what I want is impossible at the moment. I might be more successful writing code directly in C and than calling from under Mathematica... – István Zachar – 2013-08-26T21:52:48.120

Yea :( Perhaps passing the globals in the Compiled functions and then replace them with pointers in the CCodeStringGenerate can save some (writing) time. – ssch – 2013-08-26T22:00:46.843

No answers