lshifr
12/17/2016 - 5:57 PM

An answer for the question http://mathematica.stackexchange.com/q/133670/81

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}  *)
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];