3
$\begingroup$

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?

$\endgroup$
  • 2
    $\begingroup$ With an Association <|"dog" -> Sin[0.17], "cat" -> Cos[0.18], "frog" -> 17|>? Try not to focus on compilation before exhausting built-in functions. $\endgroup$ – Roman Oct 28 '19 at 16:31
  • $\begingroup$ @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. $\endgroup$ – Igor Rivin Oct 28 '19 at 17:44
4
$\begingroup$

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
$\endgroup$
  • $\begingroup$ Aha! Now you are talking! That is very cool! $\endgroup$ – Igor Rivin Oct 28 '19 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.