6
$\begingroup$

Is there a way in Mathematica to convert prefix to infix notation (where precedence order is preserved)?

For example, how would I convert S[a, S[b, c]] to a ~ S ~ (b ~ S ~ c)?

I checked the cookbook and also on line for "prefix to infix transformation". but did not find this topic.

$\endgroup$
3
  • $\begingroup$ I noted that Infix[S[Infix[S[a, b]], c]] produces (a ~ S ~ b) ~ S ~ c So it's a matter of nesting the Infix operation in this way. Not sure how to achieve it in Mathematica. $\endgroup$
    – Michel
    Feb 11, 2019 at 21:43
  • $\begingroup$ Perhaps via MapAll? But then only applied to non atomic (non leaf) parts? $\endgroup$
    – Michel
    Feb 11, 2019 at 21:49
  • $\begingroup$ MapAll[Infix, S[a, S[b, c]]] gives Infix[a] ~ S ~ (Infix[b] ~ S ~ Infix[c]) so my remaining question is how to not apply Infix to a, b and c. $\endgroup$
    – Michel
    Feb 11, 2019 at 21:54

2 Answers 2

7
$\begingroup$
With[{S = Infix[S[##]] &}, S[a, S[b, c]] ]

a ~S~ (b ~S~ c)

Also

S[a, S[b, c]] /. S -> (Infix[S[##]] &)

a ~S~ (b ~S~ c)

$\endgroup$
3
  • $\begingroup$ Thank you, that's helpful. I will go with the second option. $\endgroup$
    – Michel
    Feb 11, 2019 at 22:02
  • 2
    $\begingroup$ Slightly neater is S -> Infix @* S. $\endgroup$
    – Carl Woll
    Feb 13, 2019 at 18:11
  • $\begingroup$ @CarlWoll, yes!! Thank you. $\endgroup$
    – kglr
    Feb 14, 2019 at 18:54
4
$\begingroup$

You could just give S a format:

MakeBoxes[S[a_, b_], StandardForm] ^:= MakeBoxes[Infix[S[a, b]], StandardForm]

Then:

S[a, S[b, c]]

a ~S~ (b ~S~ c)

$\endgroup$
1
  • $\begingroup$ Thanks much appreciated. $\endgroup$
    – Michel
    Feb 13, 2019 at 13:04

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.