I defined a function in Mathematica to process a pre-generated string. More specifically, I'd like to process some parts of C codes generated from MMA. Basically what my function does is to expand the pow function in C, so it involves finding a string pattern and replacing it. I know using MMA is not the best way to solve this problem, but unfortunately the language I'm most familiar with is MMA...Anyway, here's my function:
ExpandPowInCode[code_] := StringReplace[code, Shortest["pow(" ~~ x__ ~~ "," ~~ y__ ~~ ")"] -> If[StringMatchQ[x, ___ ~~ "+" ~~ __] || StringMatchQ[x, ___ ~~ "-" ~~ __], Nest[StringJoin["(" <> ToString[x] <> ")", "*" ~~ #] &, "(" <> ToString[x] <> ")", ToExpression[y, InputForm] - 1], Nest[StringJoin[x, "*" ~~ #] &, x, ToExpression[y, InputForm] - 1]]] It works as I expected, namely expanding , for example, "pow(x,2)" into "x*x". The If condition will help when dealing with plus/minus sign in the first argument of pow. For example,
ExpandPowInCode["pow(a x+b,3)"]
"(a x+b)*(a x+b)*(a x+b)"
However, at the first time I executed ExpandPowInCode, I always got the following error messages:
StringMatchQ::strse: String or list of strings expected at position 1 in StringMatchQ[x,___~~+~~__]. >>
StringMatchQ::strse: String or list of strings expected at position 1 in StringMatchQ[x,___~~-~~__]. >>
Although ExpandPowInCode still gave me the correct result, the appearance of error messages was really annoying...Moreover, when I executed the function again later, the error messages no longer appeared as if everything were correct. Has anyone ever met this odd situation?
->with:>... $\endgroup$->the error messages only appeared once? Shouldn't they pop out every time I execute it? $\endgroup$ExpandPowInCode[code_String] := StringReplace[code, RegularExpression["pow\\((.+?),(\\s*)(\\d+)\\)"] :> ToString[Row[ConstantArray["(" <> "$1" <> ")", ToExpression["$3"]], "*"]]]$\endgroup$TraceScan[Print, ExpandPowInCode["pow(a x+b,3)"]]twice, you can see at what point in the execution the difference is occuring. It is, not surprisingly, diverging some time before the error occurs, just afterShortest[pow(~~x__~~,~~y__~~)]. $\endgroup$