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:
Unprotect[Plus]
Plus[2, 2] := 5
Unprotect[Integer]
2 + 2 ^= 5
This book suggests that Plus and Times have special rules. Is this really impossible to do?
Answer
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]];
Unprotect[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.
Comments
Post a Comment