4
$\begingroup$

I'm trying to use Mathematica as a tool to prove that some C code is equivalent to another (up to roundoff errors). For this I need to somehow paste C expressions like sqrt(sqr(x)+y*z). I.e. the expressions that contain function calls.

There's a set of functions I know beforehand, and I would like to make it possible to use them as some objects which, on being multiplied on the right by something, result in applying functions instead of multiplication. I.e. I need to make the above expression automatically convert to Sqrt[square[x]+y z].

How can I achieve this? Note: I'm not looking for a complete C-to-Wolfram translator. Only this particular function-call syntax with particular function names.

$\endgroup$
6
$\begingroup$

There is a handy package, Notation, built-in to Mathematica. With it, we can do the following:

Needs["Notation`"]

Notation[ParsedBoxWrapper[RowBox[{"sqrt", RowBox[{"(", "x_", ")"}]}]]
         ⟹
         ParsedBoxWrapper[SqrtBox["x_"]]]

Notation[ParsedBoxWrapper[RowBox[{"sqr",  RowBox[{"(", "x_", ")"}]}]]
         ⟹
         ParsedBoxWrapper[SuperscriptBox["x_", "2"]]]

In the Mathematica Notebook interface, it looks like this (after Needs["Notation`"] has been executed, and then you selected the Notation[...] and pressed Ctrl+Shift+N):

screenshot

After entering this code, we can simply do

d = sqrt(sqr(a)+2*a*R)

and get our output

Sqrt[a^2 + 2 a R]

$\endgroup$
3
$\begingroup$

Maybe you can use the fact that TraditionalForm by default interprets parentheses as function calls:

fromCString[s_String] := ReplaceAll[
    ToExpression[s, TraditionalForm, Defer],
    {
        sqrt -> Sqrt,
        sqr -> square
    }
]

Then:

fromCString["sqrt(sqr(x)+y*z)"]

Sqrt[square[x] + y z]

$\endgroup$

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.