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
    $\begingroup$ Answering your deleted comment.try Fu[a_, b_, o_] := Module[{}, Unevaluated[a + b] /. Plus -> o]; Fu[4, 2, Times] $\endgroup$ – Dr. belisarius Apr 7 '13 at 20:16
18
$\begingroup$

Perhaps use the full names for the operators:

a * b /. Times -> Plus

a + b

$\endgroup$
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$
  • $\begingroup$ c = Defer[a + b]; How come c + 3 doesn't return 8? $\endgroup$ – BoLe Apr 7 '13 at 17:09
  • $\begingroup$ @BoLe: execute c + 3 // FullForm and see. $\endgroup$ – J. M. will be back soon Apr 7 '13 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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