Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lshifr
Created December 17, 2016 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lshifr/7b2cc08fd7697a02c512249beba022a1 to your computer and use it in GitHub Desktop.
Save lshifr/7b2cc08fd7697a02c512249beba022a1 to your computer and use it in GitHub Desktop.
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