# Compile[] with non-numeric arguments

Suppose I have a function like this foo[x_]:=Switch[x, "dog", Sin[0.17], "cat", Cos[0.18], "frog", 17]. Compiling it won't work, since the argument is a string. Obviously, one can manually encode the set of possible input strings as numbers, possibly with the help of FeatureExtraction, but is there any fully automatic (or programmatic, if you prefer) way of dealing with this?

• With an Association <|"dog" -> Sin[0.17], "cat" -> Cos[0.18], "frog" -> 17|>? Try not to focus on compilation before exhausting built-in functions. – Roman Oct 28 '19 at 16:31
• @Roman You seem to be missing the point. The "real" function would be a lot more complicated, so each entry in the association would be very slow. Yes, one can compile each branch into a separate function, but then the dispatch would still be interpreted, so the result would be both ugly and slow. – Igor Rivin Oct 28 '19 at 17:44

If you have a list of string/function pairs

L = {{"dog", (Pause[1]; #) &},
{"cat", (Pause[1]; #)^2 &},
{"frog", (Pause[1]; #)^3 &}};


this will automatically generate a precompiled Dispatch table to make the lookup super-fast:

Clear[foo];
(foo[#[[1]]] = #[[2]]) & /@ L;


Test:

?foo
(*    definitions    *)

foo["cat"][5]
(*    25    *)

foo["frog"][5]
(*    125    *)


If the functions in L are uncompiled, you can also compile them while assigning them to foo:

Clear[foo];
(foo[#[[1]]] = Compile[x, Evaluate[#[[2]][x]]]) & /@ L;
?foo

• Aha! Now you are talking! That is very cool! – Igor Rivin Oct 28 '19 at 21:22