Infix[]
works only at first level:
Infix[(c a^b)^d]
(*
-> (a^b c) ~Power~ d
*)
As I want to (don't ask why) get the full expression switched to infix notation, I tried something like:
SetAttributes[toInfx, HoldAll];
toInfx[expr_] := Module[{prfx, infx},
prfx = Level[expr, {0, Infinity}];
infx = Infix /@ prfx /. {Infix[a_Symbol] -> a, Infix[a_?NumericQ] -> a};
Fold[ReplaceAll[#1, #2] &, expr, Reverse@Thread[Rule[prfx, infx]]]
]
k = toInfx[(c a^b)^d]
(*
-> (c ~Times~ (a ~Power~ b)) ~Power~ d
*)
But this has two evident problems, because
(c a^b)^d == a~Power~b~Times~c~Power~d
k = toInfx[a/b + ArcTan[a/b]]
Is there an easy way to get Infix[]
working for All (leaves)?
Here's my approach, very similar to Leonid's:
(* In[118]:= *) foo[a:_[_,__]]:=Infix[a]
foo[a_]:=a
(* In[120]:= *) MapAll[foo,(c a^b)^d]
(* Out[120]= *) (c ~Times~ (a ~Power~ b)) ~Power~ d
(* In[121]:= *) MapAll[foo,a/b+ArcTan[a/b]]
(* Out[121]= *) ArcTan[a ~Times~ (b ~Power~ (-1))] ~Plus~ (a ~Times~ (b ~Power~ (-1)))
Here is one way:
ClearAll[toInfixAlt];
SetAttributes[toInfixAlt, HoldAll];
toInfixAlt[expr_] :=
First@MapAll[Infix, HoldForm[expr]] //.
Infix[a : _?(Function[s, AtomQ[Unevaluated@s], HoldAll]) | _[_]| _[]] :> a
I used HoldForm
since you may want the code to remain unevaluated. Here is an example:
In[781]:= toInfixAlt[(c a^b)^d/(1/2)]
Out[781]= ((c ~Times~ (a ~Power~ b)) ~Power~ d) ~Times~ (1/((1/2)))
EDIT
and,
In[792]:= toInfixAlt[a/b+ArcTan[a/b]]
Out[792]= (a ~Times~ (b ~Power~ (-1))) ~Plus~ ArcTan[a ~Times~ (b ~Power~ (-1))]
End EDIT
As to the superfluous parentheses, it is harder to remove them since often they are indeed needed due to precedence of various operators, but should be possible.
EDIT 2
To take care of precedence, here is an attempt:
ClearAll[toInfixAlt];
SetAttributes[toInfixAlt, HoldAll];
toInfixAlt[expr_] :=
First@MapAll[Infix, HoldForm[expr]] //.
Infix[a : _?(Function[s, AtomQ[Unevaluated@s],HoldAll]) | _[_] | _[]] :> a //.
{
Infix[f_[a__, Infix[r : (h_[___])],b___]] /;
Precedence[Unevaluated[f]] <= Precedence[Unevaluated[h]] :> Infix[f[a, r, b]],
Infix[b___,f_[Infix[r : (h_[___])], a__]] /;
Precedence[Unevaluated[f]] <= Precedence[Unevaluated[h]] :> Infix[f[b, r, a]]
};
Now, I get:
In[963]:= toInfixAlt[a/b+ArcTan[a/b]]
Out[963]= (a b ~Power~ (-1)) ~Plus~ ArcTan[a ~Times~ (1/b)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With