Recently I have met with with this interesting question:How can I efficiently define functions with different names but doing the same stuff? Somebody may want to ask me why I want to do things like this, actually it is very much meaningful.
For example, there are 3 built-in functions in MMA: ContourIntegral[]
,ClockwiseContourIntegral[]
,CounterClockwiseContourIntegral[]
. None of them has attached to any evaluation rules but they exist to stand for different external notations.
And what I am doing now is to define evaluation rules to those 3 integrals, or the so called "down values" of them. And I found that although with different names and external notations, when it comes to evaluation, they are the same: all of them are line integrals. As a result, the evaluation rules of them can also be the same both in their argument and functional body. But currently, I have to write 3 different lines doing the same thing, for instance:
ContourIntegral[x_]:=x^2+x;
ClockwiseContourIntegral[x_]:=x^2+x;
CounterClockwiseContourIntegral[x_]:=x^2+x;
(Since the name of the 3 integrals are somewhat long, I instead use f[]
, g[]
,h[]
hereafter)
The way of coding above works, but verbose and wordy, since they are doing the same thing only with their function name different.
Moreover, when it comes to code maintenance, one change in code will lead you to modify code in 3 lines one by one. But if you can do it in one line, you can only change once in this very line to finish the maintenance efficiently.
To achieve this goal, I have tried to write in one line like :
(f||g||h)[x_]:=x^2+x;
(f|g|h)[x_]:=x^2+x;
(f[x_]||g[x_]||h[x_]):=x^2+x
Unfortunately, none of above works. And some of the error message:
So any idea on how to tell MMA that those functions doing the same thing but only with different names (or heads) in one line?
SetDelayed
use(#[x_] := x^2 + x) & /@ {f, g, h};
$\endgroup$