Function Repository Resource:

ArgumentCount

Source Notebook

Count the number of arguments a pure function or compiled function takes

Contributed by: Sjoerd Smit

ResourceFunction["ArgumentCount"][Function[]]

counts how many arguments the given function takes.

Details and Options

ResourceFunction["ArgumentCount"] works with CompiledFunction and CompiledCodeFunction.
If a Function uses SlotSequence, the returned argument count will be ∞ unless the option "IgnoreSlotSequence" True is set.

Examples

Basic Examples (2) 

Find the highest numbered slot in a function:

In[1]:=
ResourceFunction["ArgumentCount"][Function[#^2]]
Out[1]=
In[2]:=
ResourceFunction["ArgumentCount"][Function[#1 + #2]]
Out[2]=
In[3]:=
ResourceFunction["ArgumentCount"][Function[{x, y, z}, Sin[x + y/z]]]
Out[3]=

In this function, slot 2 goes unused, but it will still be counted:

In[4]:=
ResourceFunction["ArgumentCount"][Function[#1 + #3]]
Out[4]=

Scope (4) 

Slots in inner functions will not be counted:

In[5]:=
ResourceFunction["ArgumentCount"][
 Function[
  Function[#1 + #2 + #3][#1, 2 #1, 3 #1]
  ]
 ]
Out[5]=

A function that uses SlotSequence will be counted as having infinite arguments:

In[6]:=
ResourceFunction["ArgumentCount"][Function[Plus[##]]]
Out[6]=

String slots will be counted as being part of the first argument:

In[7]:=
ResourceFunction["ArgumentCount"][Function[#a  + #b]]
Out[7]=
In[8]:=
ResourceFunction["ArgumentCount"][Function[#a  + #b + #2]]
Out[8]=

ArgumentCount works with compiled functions:

In[9]:=
ResourceFunction["ArgumentCount"][Compile[{x, y, z}, Sqrt[x y z]]]
Out[9]=

Options (2) 

IgnoreSlotSequence (2) 

A function that uses SlotSequence will be counted as having infinite arguments:

In[10]:=
ResourceFunction["ArgumentCount"][Function[Plus[#1, #2, ##]]]
Out[10]=

This behavior can be changed with the "IgnoreSlotSequence" option:

In[11]:=
ResourceFunction["ArgumentCount"][Function[Plus[#1, #2, ##]], "IgnoreSlotSequence" -> True]
Out[11]=

Publisher

Sjoerd Smit

Version History

  • 1.0.1 – 01 March 2021
  • 1.0.0 – 29 May 2019

Related Resources

License Information