Re: Compile for different parameter types

*To*: mathgroup at smc.vnet.net*Subject*: [mg97434] Re: Compile for different parameter types*From*: Albert Retey <awnl at gmx-topmail.de>*Date*: Fri, 13 Mar 2009 04:49:49 -0500 (EST)*References*: <gpacur$mu6$1@smc.vnet.net> <gpaot1$qe0$1@smc.vnet.net>

Hi, > This idea is kinda silly but: I just wanted to show that the idea of Raffy can just as well be done without writing the actual body (expr in the code below) of the compiled function as a string, which makes it look somewhat less silly :-) (to me at least) > funcString[a_Integer,b_Integer]:="Compile[{{A,_Real,"<>ToString[a]<>"}, > {B,_Real,"<>ToString[b]<>"}}, expr]"; funcExpr[a_Integer, b_Integer] = Hold[{{A, _Real, a}, {B, _Real, b}}, expr]; > cache[a_Integer,b_Integer]:=cache[a,b]=ToExpression[funcString[a,b]]; cache[a_Integer, b_Integer] := cache[a, b] = Compile @@ funcExpr[a, b]; > func[a_?ArrayQ,b_?ArrayQ]:=cache[ArrayDepth[a],ArrayDepth[b]][a,b]; this last one needs no modification. For the reasons Jens has explained, I think automatically creating the compiled functions when needed as Raffy suggested is probably the best you can do. Just don't forget to ClearAll[cache] after changing expr... For some reasons I think it is good practice to try to avoid ToExpression and work with Mathematica expressions instead of strings wherever possible. Usually this can be done conveniently with placing some Holds in the right places. Some advantages are that syntax highlighting and 2D-Input for formulas will work as usual within the body of your compiled function, but it will also avoid parsing "expr" each and every time funcString is called. I also found that code using ToExpression is more error prone than code without it, especially when working with Packages/Contexts. Other problems with ToExpression can arise when using your code with Player, PlayerPro or WebMathematica, where ToExpression is limited to work with a subset of Mathematica only. There might be many more and probably even better reasons to try to avoid ToExpression, but I can't think of any more right now... hth, albert