/.
can be used to replace variables but how can one replace operators.
For example in a * b
, *
can be replaced by +
or x
or /
etc. Is there some function to achieve this?
Perhaps use the full names for the operators:
a * b /. Times -> Plus
a + b
FullForm
prints the expression with no special syntax (e.g. Plus
instead of +
).
FullForm[a*b]
(* Times[a, b] *)
So you change the expression's head.
Table[fun @@ (a*b),
{fun, {Plus, Subtract, Divide, Dot, Cross}}]
(* {a + b, a - b, a/b, a.b, a\[Cross]b} *)
Just to complement: be careful when your symbols have values already assigned.
Compare:
a = 2; b = 3; rule = Plus -> Times;
a + b /. rule
ReleaseHold[Hold[a + b] /. rule]
Unevaluated[a + b] /. rule
Defer[a + b] /. rule
(*
5
6
6
a b
*)
c = Defer[a + b];
How come c + 3
doesn't return 8?
$\endgroup$
c + 3 // FullForm
and see.
$\endgroup$
Commented
Apr 7, 2013 at 17:16
Fu[a_, b_, o_] := Module[{}, Unevaluated[a + b] /. Plus -> o]; Fu[4, 2, Times]
$\endgroup$