Yes, for both named patterns and pure functions.
Pure functions
You can see that inherently they accept multiple arguments but discard those that are not used:
{#} &[1, 2, 3] (* out: {1} *)
The object ##
, (SlotSequence
), represents all arguments wrapped in Sequence
, e.g. Sequence[1, 2, 3]
. (Internally it doesn't use Sequence
but it behaves similarly in most places.)
{##} &[1, 2, 3] (* out: {1, 2, 3} *)
You can combine #
and ##
, including their numbered forms:
{"first" -> #, "rest" -> {##2}, "all" -> {##}} &[1, 2, 3]
{"first" -> 1, "rest" -> {2, 3}, "all" -> {1, 2, 3}}
Named patterns
Using Blank*
:
_
(Blank
)
__
(BlankSequence
)
___
(BlankNullSequence
):
f[a_, b__] := {"first" -> a, "rest" -> {b}}
f[1, 2, 3] (* out: {"first" -> 1, "rest" -> {2, 3}} *)
__
requires an argument to be present while ___
does not:
f[1] (* out: f[1] *)
g[a_, b___] := {"first" -> a, "rest" -> {b}}
g[1] (* out: {"first" -> 1, "rest" -> {}} *)
Multiple variable length named patterns can be given and will by default be matched shortest first:
h[a_, b__, c__] := {"a" -> a, "b" -> {b}, "c" -> {c}}
h[1, 2, 3, 4, 5] (* out: {"a" -> 1, "b" -> {2}, "c" -> {3, 4, 5}} *)
This can be controlled with Shortest
and Longest
:
i[a_, Longest[b__], c__] := {"a" -> a, "b" -> {b}, "c" -> {c}}
i[1, 2, 3, 4, 5] (* out: {"a" -> 1, "b" -> {2, 3, 4}, "c" -> {5}} *)
See this answer for an advanced use of these functions.
The Blank*
functions are not the only way to create a variable length pattern. You can also use Repeated
(..
) or RepeatedNull
(...
):
j[x : _Real ..] := {x}
j[1.1, 1.2, 1.3] (* out: {1.1, 1.2, 1.3} *)
These methods can be used in powerful ways such as destructuring.
Optional arguments
In addition to the variable length methods above one can make use of Optional
parameters with or without the use of Default
values. A basic example:
k[a_, b_: 3, c_: 5] := {a, b, c}
k[1]
k[1, 2]
k[1, 2, 3]
{1, 3, 5}
{1, 2, 5}
{1, 2, 3}
In the example above there are two optional parameters. By default they are filled in sequential order, meaning that in k[1, 2]
the 2
is bound to b
. This also can be controlled with Shortest
and Longest
as noted in the section above.
In a limited way optional arguments can also be used for pure functions:
Default
can be used to set the default values for a given function, rather than specifying them as part of each function definition, but it must be used before they are defined, and it cannot be used to change them for existing definitions. (Why does Default behave like this?)
Default[m, 1] = 1;
Default[m, 2] = 3;
Default[m, 3] = 5;
m[a_., b_., c_.] := {a, b, c}
m[]
m[2]
m[2, 4]
m[2, 4, 6]
{1, 3, 5}
{2, 3, 5}
{2, 4, 5}
{2, 4, 6}
Also see:
Related Q&A's of a more advanced nature: