1
$\begingroup$

I have created a package that consists of a function which uses Compile. This function contains a parameter, say a, and I want to call the package in an notebook environment and define a in the notebook.

So far I define this parameter within the package as a=Global`a and I call the package with Get.

The problem is now that I want to initialize or load the package at the very beginning of my notebook and just later determine the value of a. In order that the function is compilable I need to reload the package a second time after assigning a value to a. Is it possible that the internal code in the package automatically takes over the value of a without calling it a second time in the notebook environment? I tried something like a:=Global`a but it does not seem to work.

What would be the common approach to such a problem.

Edit

Of course, I could initialize the parameter first, before I call the package. Though I wonder whether there is a solution if I do it the other way round.

$\endgroup$
  • 2
    $\begingroup$ Can you show us a minimal example? $\endgroup$ – xzczd Jun 11 '18 at 12:05
  • 1
    $\begingroup$ Side note: Passing information to a package via global variables somehow defeats the purpose making it a separate unit in the first place… Wouldn't something like a public variable within the package or even a "configure[…]" function be a better way to handle things? Of course, this alone doesn't fix the issue in the question $\endgroup$ – Lukas Lang Jun 11 '18 at 12:23
  • 1
    $\begingroup$ To give a meaningful answer, at least the outline how you defined the compiled function and where and how it uses the parameter a would really help. You don't need to include the whole definition of your compiled function, but it must be clear how you use the value of a inside your package. $\endgroup$ – halirutan Jun 11 '18 at 12:51
  • 2
    $\begingroup$ Passing a variable as a global variable to a CompiledFunction is a very bad idea because this will cause calls to the main evaluator which 1.) makes the compiled function slow and 2.) it makes parallelization of it impossible. Include a to the argument pattern of the compiled function and everything should work out fine. $\endgroup$ – Henrik Schumacher Jun 11 '18 at 13:57
4
$\begingroup$

Are you perhaps groping toward partial evaluation? How about

generalFunc[a_]:=Compile[{b}, something containing a and b]

in your package. This defers compilation until you do something like:

specificFunc = generalFunc[2];

which substitutes 2 for a in your function and then compiles it, yielding a function only of b.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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