Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I was looking at this question (writing a program such that 2 + 2 = 5) and tried to write something in Mathematica, but I couldn't get something to work without completely replacing Plus. Neither of these worked:

Plus[2, 2] := 5
2 + 2 ^= 5

This book suggests that Plus and Times have special rules. Is this really impossible to do?

share|improve this question
Something like Block[{Plus = Times}, 2 + 3] – Jacob Akkerboom Jun 2 '14 at 11:25
@JacobAkkerboom that's what I meant with "completely replacing Plus" – Artefacto Jun 2 '14 at 12:13
up vote 8 down vote accepted

Another solution for this weird exercise is to make a combination from using $Pre and defining a new plus function. You use $Pre to replace every occurrence of Plus by your own definition which only act special at the input plus[2,2] and calls the normal Plus otherwise:

SetAttributes[plus, Attributes[Plus]];
plus[2, 2] = 5;
plus[args___] := Plus[args];
$Pre = Function[Null,
   ReleaseHold[Hold[#] /. Plus :> plus], HoldAllComplete];

Now, the obvious input 2+2 works as well as e.g. 4/2 + (6 - 4) but I wouldn't bet that this works in all circumstances.

share|improve this answer
A simpler use of \$Pre would be just \$Pre = (# /. Plus[2, 2] :> 5) & – Bob Hanlon Jun 2 '14 at 21:57
Presumably, because Function has the attribute HoldAll. – Bob Hanlon Jun 3 '14 at 14:36
@BobHanlon That solution won't work unless you use HoldPattern and set the attribute HoldAll on the function, as in $Pre = Function[x, Unevaluated[x] /. HoldPattern@Plus[2, 2] :> 5, HoldAll]. Otherwise it will only replace the input 4 with 5, not replace 2+2 with 5. Consider the input 3(2+2) or the input 4. – Szabolcs Jun 4 '14 at 14:44
Disregard my original comment. – Bob Hanlon Jun 4 '14 at 17:05

How about this ;-)

share|improve this answer
This one made me laugh. Very creative! – Oleksandr R. Jun 2 '14 at 22:38

This works:

mp[2, 2] = 5
Block[{Plus = mp}, 2 + 2]

Now of course the interesting question is why Unprotect does not work as expected? I have not yet figured it out. Nothing special is seen in the Attributes. Actually doing

Plus[2, 2] = 5

shows the new rule.

share|improve this answer
Plus is handled specially and is subject to all sorts of evaluation shortcuts, at least for numeric arguments. In this case it would probably be better to think of the definitions as showing you how Plus behaves, rather than that the behavior actually comes from those definitions as in the usual case. – Oleksandr R. Jun 2 '14 at 22:42

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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