Skip to main content

expression manipulation - Construct an infix operation from a list



Inspired by this question, if I have a list


{a, p, b, q, c}

where p and q are binary operators, such as Plus and Times, how would I construct the expression


a ~ p ~ b ~ q ~ c

and execute it?


Obviously, the solution proposed in the other question of constructing it via strings is the most straightforward approach, but I would like to know if the infix formulation, above, is doable without resorting to string manipulation.



Answer



Two variants:



(* left-associative *)
Hold[a, Times, b, Plus, c, Subtract, f] //. f_[a_, p_, b_, c___] :> f[p[a, b], c]
(* Hold[(a b + c) - f] *)

(* right-associative *)
Hold[a, Times, b, Plus, c, Subtract, f] //. f_[c___, a_, p_, b_] :> f[c, p[a, b]]
(* Hold[a (b + (c - f))] *)

after which one can apply ReleaseHold[]...


Comments