Created
December 17, 2016 17:57
-
-
Save lshifr/7b2cc08fd7697a02c512249beba022a1 to your computer and use it in GitHub Desktop.
An answer for the question http://mathematica.stackexchange.com/q/133670/81
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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