I often see in code by other people some standard functions like Sum, NonCommutativeMultiply etc get unprotected, supplemented by additional rules and then protected back. It is not clear to be that this is a good idea. How can I be sure that I will not mess up badly redefining something like Sum? Is not there a way to somehow clone the command say "mySum=Sum" and then make changes to the new command? Or maybe there is a way to modify an existing command locally, say within some scoping construct?
- 535
- 2
- 15
1 Answers
Is it a good idea to unprotect standard commands?
No, it is not usually a good idea to modify built-ins. If you modify a built-in, other built-ins (or packages) that rely on it may either break or may slow down significantly. Here's an example of such a slowdown:
If you are just looking to overload a built-in for your own custom expression type, consider using up-values instead.
Of course, there are some built-ins which are designed to be extended, e.g. MakeBoxes. That's an entirely different situation. You may also want to intercept the calls to some functions to better understand how the system works. That is also a reasonable application. However, if you were to publish a package in which you overload a fundamental function such as Sum, I would think twice before using your package.
Is not there a way to somehow clone the command say "
mySum=Sum" and then make changes to the new command?
You don't need to "clone" it. Simply use Sum in the definition of mySum.
- 234,956
- 30
- 623
- 1,263
-
Just to clarify. If I want to take standard
NonCommutativeMultiplyand then make it do whatever I want, I can just initializemyNCM[x___]:=NonCommutativeMultiply[x]and then do withmyNCMwhatever I want? – Weather Report Aug 11 '20 at 17:01 -
1@WeatherReport No.
NonCommutativeMultiplydoes not do anything, so there is no point to calling it from another function.NonCommutativeMultiplyis one of those symbols which is meant to be given a definition (it does not have one by default). Just use it. – Szabolcs Aug 11 '20 at 21:07
Internal`InheritedBlockto temporarily change built-in functions without permanent damage: https://mathematica.stackexchange.com/q/25769/43522 – Sjoerd Smit Aug 11 '20 at 14:09IntegrateinsideDSolveor [to change theMethodof `Solve](https://mathematica.stackexchange.com/a/63676/4999) insideDSolve. The alternative is that Mathematica fails. In their limited use-cases, altering built-ins seem worth the risk. But there is a risk. – Michael E2 Aug 11 '20 at 14:20