In Mathematica, you can construct a function f
to have different definitions based on its input arguments. For example, f[x_] := ...
and f[x_, y_] := ...
. You can also get more specific and define it for specific heads as f[x_someHead] := ...
or inputs matching arbitrary patterns as f[x_?somePatternQ] := ...
(of course, one must be careful to keep the order from specific to general). These definitions are the DownValues
of the function.
Now, I'd like to construct a function that has different definitions based on the number of output variables/symbols requested, but for the same set of inputs. Consider the following dummy example in pseudo Mathematica code
f[mu_, sigma2_] := Switch[OutputArgs[],
0, Plot[PDF[NormalDistribution[mu, sigma2], x], ...]
1, RandomReal[NormalDistribution[mu, sigma2], 1000]
2, {Mean@#, Variance@#}&@ RandomReal[...]
]
Here OutputArgs[]
is a functionality that I'd like, which when called from inside a function, tells you how many outputs have been requested (loosely reminiscent of OptionValue
which knows which function it's called from). With this, I can use the function call simply as f[0,1]
to plot the normal distribution (perhaps inside a Manipulate
to play with the parameters), then when I'm satisfied, I can use the same function call, but with an output argument as a = f[0,1]
to get a random sample, and with two outputs to get an empirical estimate of the mean and variance.
I realize that this is a bit at odds with the classical notion of a function having a well defined output based on the input, rather than a well defined output based on the number of outputs for a given input.
My interest is purely academic and arose from working on porting some MATLAB code to Mathematica. Some might have recognized that right away, and this is a feature that that I do find useful — a sentiment also shared by a few others that I've spoken to here. I wouldn't write code this way and I know that it is also possible to achieve the same by other means such as using flags as f[0, 1, "Plot"]
or options as f[0, 1, Options -> "RandomSample"]
, etc. for the above example. However, I'm interested in exploring if there are ways to imitate this behaviour in Mathematica.
OutputArgs[]
? I don't know how to "know" from within the function how many outputs are requested. As for advantages, I don't think there are any, and if I write a function, I probably would do it with options. This thought occurred when I tried to port a script to mma, and I was puzzling over how one would go about doing it, if so desired. $\endgroup$