Macaulay2 » Documentation
Packages » Macaulay2Doc > The Macaulay2 language > making functions with a variable number of arguments
next | previous | forward | backward | up | index | toc

making functions with a variable number of arguments

It is easy to write a function with a variable number of arguments. Define the function with just one parameter, with no parentheses around it. If the function is called with several arguments, the value of the single parameter will be a sequence containing the several arguments; if the function is called with one argument, the value of the parameter will be that single argument.
i1 : f = x -> {class x, if class x === Sequence then #x};
i2 : f()

o2 = {Sequence, 0}

o2 : List
i3 : f(3)

o3 = {ZZ, }

o3 : List
i4 : f(3,4)

o4 = {Sequence, 2}

o4 : List
i5 : f(3,4,5)

o5 = {Sequence, 3}

o5 : List
We could use the function sequence to bring the case where there is just one argument into line with the others. It will enclose anything that is not a sequence in a sequence of length one.
i6 : f = x -> (
          x = sequence x;
          {class x, #x});
i7 : f()

o7 = {Sequence, 0}

o7 : List
i8 : f(3)

o8 = {Sequence, 1}

o8 : List
i9 : f(3,4)

o9 = {Sequence, 2}

o9 : List
i10 : f(3,4,5)

o10 = {Sequence, 3}

o10 : List
As an aside, we reveal that there is a way to define a function of one argument that will signal an error if it's given more than one argument: put parentheses around the single parameter in the definition of the function. As a side effect it can be used to extract the single element from a singleton sequence.
i11 : ((x) -> x) 3

o11 = 3
i12 : 1 : 3

o12 = 1 : (3)

o12 : Sequence
i13 : ((x) -> x) oo

o13 = 3