How to Define Variadic Functions in Julia
Overview 1
A Varargs Function, commonly mentioned in programming, is a function that can receive an unlimited number of arguments. In Julia, you can simply set a variable to accept variadic arguments by appending ...
after it. Let’s understand this with an example code.
Additionally, this ...
is called splat operator.2
Code
Isaac Newton famously discovered that adding the reciprocals of factorials simply converges to $e$ with the following theorem. $$ e = {{ 1 } \over { 0! }} + {{ 1 } \over { 1! }} + {{ 1 } \over { 2! }} + \cdots = \sum_{k=0}^{\infty} {{ 1 } \over { k! }} $$ In this example, we will look at a sequence converging to Euler’s constant $e = 2.71828182 \cdots$.
function f(x...)
zeta = 0
for x_ in x
zeta += 1/prod(1:x_)
end
return zeta
end
As shown above, appending a dot after x
to write x...
automatically considers the given arguments as an array. The content of the function is as seen in the equation above, simply taking the reciprocal of factorials in order and adding them to return.
julia> f(0)
1.0
julia> f(0,1)
2.0
julia> f(0,1,2)
2.5
julia> f(0,1,2,3,4,5,6,7,8,9,10)
2.7182818011463845
The execution result shows that as natural numbers are given longer, it gets closer to Euler’s constant. It’s noteworthy here that the variably entered arguments are automatically bundled into an array called x
. For example, putting an array conceptually like the following could result in an error.
julia> f(0:10)
ERROR: MethodError: no method matching (::Colon)(::Int64, ::UnitRange{Int64})
Environment
- OS: Windows
- julia: v1.6.3