11
$\begingroup$

/. 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?

$\endgroup$
1
  • 1
    $\begingroup$ Answering your deleted comment.try Fu[a_, b_, o_] := Module[{}, Unevaluated[a + b] /. Plus -> o]; Fu[4, 2, Times] $\endgroup$ Commented Apr 7, 2013 at 20:16

3 Answers 3

19
$\begingroup$

Perhaps use the full names for the operators:

a * b /. Times -> Plus

a + b

$\endgroup$
0
7
$\begingroup$

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} *)
$\endgroup$
3
$\begingroup$

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
*)
$\endgroup$
2
  • $\begingroup$ c = Defer[a + b]; How come c + 3 doesn't return 8? $\endgroup$
    – BoLe
    Commented Apr 7, 2013 at 17:09
  • $\begingroup$ @BoLe: execute c + 3 // FullForm and see. $\endgroup$ Commented Apr 7, 2013 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.