I am trying to reproduce the API of a function (written in R) that accepts an arbitrary number of arguments and handles it the same way as it would handle a single argument that is a list of different data sets.
Is there a Mathematica idiom that allows a function to be defined so that:
f[ arg1, arg2, ..., argN ]
behaves the same as
f[ {arg1, arg2, ..., argN} ]
?
Answer
As described by Andy Ross in a comment, you can make a definition that preprocesses the argument(s) into a canonical form. Turning his example around simply to illustrate flexibility:
f[{args__}] := f[args]
f[args__] := Multinomial[args] / Plus[args]
f[{12, 7, 3}] == f[12, 7, 3]
True
This method is useful for more complicated preprocessing, but in simple cases such as this it is often easier to use Alternatives
:
g[{args__} | args__] := Multinomial[args]/Plus[args]
g[{12, 7, 3}] == g[12, 7, 3]
True
Be aware that when using Alternatives
you must manually order the patterns, for they are tried in sequence. The pattern args__ | {args__}
would not work as desired because args__
will match {12, 7, 3}
as a single argument.
Comments
Post a Comment