Function Repository Resource:

DeclareArgumentCount

Source Notebook

Set up a symbol to give an error message when called with an unexpected number of arguments

Contributed by: Taliesin Beynon

ResourceFunction["DeclareArgumentCount"][symbol,n]

specifies that symbol is a function that takes exactly n arguments.

ResourceFunction["DeclareArgumentCount"][symbol,{min,max}]

specifies that symbol takes between min and max arguments.

Details and Options

ResourceFunction["DeclareArgumentCount"][symbol,n] basically sets up a downvalue to do error reporting.
When symbol is called with the wrong number of arguments, it will issue the appropriate system message and return unevaluated.

Examples

Basic Examples (3) 

Declare that a symbol myFunc takes exactly two arguments:

In[1]:=
ResourceFunction["DeclareArgumentCount"][myFunc, 2]

When called with the correct number of arguments, the function behaves as normal:

In[2]:=
myFunc[a, b]
Out[2]=
In[3]:=
myFunc[a_, b_] := {a, b}
myFunc[1, 2]
Out[4]=

Attempting to evaluate myFunc with the incorrect argument count throws an error message and does not evaluate:

In[5]:=
myFunc[a, b, c]
Out[5]=

Properties and Relations (1) 

DeclareArgumentCount does its work by defining a downvalue for the symbol in question:

In[6]:=
ClearAll[myNewFunc]
ResourceFunction["DeclareArgumentCount"][myNewFunc, {2, 3}]
DownValues[myNewFunc]
Out[8]=

Possible Issues (2) 

The downvalue created by DeclareArgumentCount can be superseded by other downvalues in accordance with normal evaluation rules:

In[9]:=
ClearAll[myFunc3]
ResourceFunction["DeclareArgumentCount"][myFunc3, 3]
myFunc3[args___] := List[args]

Now a two-argument call does not give a message despite having declared myFunc3 to take three arguments:

In[10]:=
myFunc3[a, b]
Out[10]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 03 December 2018

License Information