Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One way it to use <code>With</code>, to create a compiled function programmatically:</p> <pre><code>Clear[makeCompiled]; makeCompiled[lnum_Integer] := With[{listNames = Table[Unique["list"], {lnum}]}, With[{compileArgs = {#, _Integer, 1} &amp; /@ listNames}, Compile @@ Join[Hold[compileArgs], Replace[Hold[Outer[Plus, listNames]], Hold[Outer[Plus, {x__}]] :&gt; Hold[Outer[Plus, x]], {0}]]]]; </code></pre> <p>It can probably be done prettier, but it works. For example:</p> <pre><code>In[22]:= p2 = makeCompiled[2] Out[22]= CompiledFunction[{list13,list14},Outer[Plus,list13,list14],-CompiledCode-] In[23]:= p2[{1,2,3},{4,5}] Out[23]= {{5,6},{6,7},{7,8}} In[24]:= p3 = makeCompiled[3] Out[24]= CompiledFunction[{list15,list16,list17},Outer[Plus,list15,list16,list17],-CompiledCode-] In[25]:= p3[{1,2},{3,4},{5,6}] Out[25]= {{{9,10},{10,11}},{{10,11},{11,12}}} </code></pre> <p>HTH</p> <p>Edit:</p> <p>You can hide the compiled function behind another one, so that it is created at run-time and you don't actually see it:</p> <pre><code>In[33]:= Clear[computeSums] computeSums[lists : {__?NumberQ} ..] := makeCompiled[Length[{lists}]][lists]; In[35]:= computeSums[{1, 2, 3}, {4, 5}] Out[35]= {{5, 6}, {6, 7}, {7, 8}} </code></pre> <p>You face an overhead of compiling in this case, since you create then a compiled function afresh every time. You can fight this overhead rather elegantly with memoization, using <code>Module</code> variables for persistence, to localize your memoized definitions:</p> <pre><code>In[44]:= Clear[computeSumsMemoized]; Module[{compiled}, compiled[n_] := compiled[n] = makeCompiled[n]; computeSumsMemoized[lists : {__?NumberQ} ..] := compiled[Length[{lists}]][lists]]; In[46]:= computeSumsMemoized[{1, 2, 3}, {4, 5}] Out[46]= {{5, 6}, {6, 7}, {7, 8}} </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload