Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infix for All (leaves)

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

  1. (c a^b)^d == a~Power~b~Times~c~Power~d
    So what I get is not an efficient use of infix.
  2. It is not robust, and fails for easy expressions such as k = toInfx[a/b + ArcTan[a/b]]

Is there an easy way to get Infix[] working for All (leaves)?

like image 876
Dr. belisarius Avatar asked Nov 27 '11 15:11

Dr. belisarius


2 Answers

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)))
like image 35
Brett Champion Avatar answered Sep 28 '22 18:09

Brett Champion


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)]
like image 80
Leonid Shifrin Avatar answered Sep 28 '22 18:09

Leonid Shifrin