Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Define a pattern expression for matching optional arguments with defaults
ResourceFunction["NameValuePattern"][a1_,a2_,…,an_,b1_:def1,b2_:def2,…,bn_:defn] makes a pattern for required arguments a1,a2,…,an and optional arguments b1,b2,…,bnwith corresponding defaults defi. |
Construct a name-value pattern with one required argument and two optional ones:
| In[1]:= |
| Out[1]= | ![]() |
Use NameValuePattern as any other pattern with functions like MatchQ or Replace:
| In[2]:= |
| Out[2]= |
| In[3]:= |
| Out[3]= |
Use head patterns:
| In[4]:= |
| Out[4]= |
Arguments with no default values bind to Sequence[]:
| In[5]:= |
| Out[5]= |
Rule can be used instead of Optional (:) to specify optional arguments:
| In[6]:= |
| Out[6]= |
RuleDelayed can be used to delay default values:
| In[7]:= |
| Out[7]= |
NameValuePattern matches the longest sequence:
| In[8]:= |
| Out[8]= |
| In[9]:= | ![]() |
| Out[9]= |
Bind to NameValuePattern as a sequence of arguments:
| In[10]:= | ![]() |
| Out[10]= |
Define a function with flexible control over its arguments:
| In[11]:= |
| In[12]:= |
| Out[12]= |
| In[13]:= |
| Out[13]= |
| In[14]:= |
| Out[14]= |
| In[15]:= |
| Out[15]= |
| In[16]:= |
| Out[16]= |
NameValuePattern can be used as an alternative to OptionsPattern:
| In[17]:= |
| In[18]:= |
| Out[18]= |
| In[19]:= |
| Out[19]= |
| In[20]:= |
| In[21]:= |
| Out[21]= |
| In[22]:= |
| Out[22]= |
But it also allows specifying required arguments by name and in any order:
| In[23]:= |
| Out[23]= |
It can also be used at any depth:
| In[24]:= |
| Out[24]= |
In certain situations rules can be interpreted literally:
| In[25]:= |
| Out[25]= |
| In[26]:= |
| Out[26]= |
| In[27]:= |
| Out[27]= |
| In[28]:= |
| Out[28]= |
| In[29]:= |
| Out[29]= |
All of the expressions here match the same pattern with bindings of symbols to their corresponding defaults:
| In[30]:= | ![]() |
| Out[30]= | ![]() |
Wolfram Language 13.0 (December 2021) or above
This work is licensed under a Creative Commons Attribution 4.0 International License