Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ClearAll[symbolRules];
symbolRules[syms_List]:=
Join @@ Map[
Function[s, symbolRules @ Unevaluated @ s, HoldFirst],
Unevaluated @ syms
]
symbolRules[sym_String]:=
ToExpression[sym, InputForm, Function[s,symbolRules @ Unevaluated @ s, HoldFirst]];
symbolRules[s_Symbol]:= Join[OwnValues[s],DownValues[s], UpValues[s], SubValues[s]];
symbolRules[]:= symbolRules @ Names["Global`*"];
ClearAll[withGlobalFunctions];
SetAttributes[withGlobalFunctions,HoldAll];
withGlobalFunctions[code_]:=
ReleaseHold @ ReplaceAll[
Hold[code],
{
HoldPattern[Map[f_Symbol,args__]] :> Map[Function[Null,f[Unevaluated @ #], HoldFirst],args],
Sequence @@ symbolRules[]
}
]
ClearAll[withCompiledFunctions];
withCompiledFunctions = Function[expr, expr /. HoldPattern[c_Compile]:> RuleCondition @ c];
ClearAll[timesC, times];
timesC = Compile[{{a, _Integer}, {b, _Real}}, a b];
times[a_, b_: 2] /; $compile := timesC[a, N[b]];
times[a_, b_: 2] := a b;
internal = Hold[
Print["Compiling..."];
Compile[{{n, _Integer}},
Table[fun[a], {a, 0, n}],
CompilationOptions -> {"InlineExternalDefinitions" -> True,
"InlineCompiledFunctions" -> True}]
];
ClearAll[external];
external[f_Function] := Block[{$compile = True},
ReleaseHold @
withCompiledFunctions@withGlobalFunctions[internal /. fun -> f]
];
Map[external[times[#] &], Range[3]]
(* During evaluation of In[163]:= Compiling... *)
(* {{0., 2.}, {0., 2., 4.}, {0., 2., 4., 6.}} *)
times /@ Range[3]
(* {2, 4, 6} *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.