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.

  • $\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$ – Mike Feb 11 '19 at 21:43
  • $\begingroup$ Perhaps via MapAll? But then only applied to non atomic (non leaf) parts? $\endgroup$ – Mike Feb 11 '19 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$ – Mike Feb 11 '19 at 21:54
With[{S = Infix[S[##]] &}, S[a, S[b, c]] ]

a ~S~ (b ~S~ c)


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

a ~S~ (b ~S~ c)

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

You could just give S a format:

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


S[a, S[b, c]]

a ~S~ (b ~S~ c)

  • $\begingroup$ Thanks much appreciated. $\endgroup$ – Mike Feb 13 '19 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.