Variadic Functions in Elm

Variadic Functions in Python

Variadic functions can be called with any number of trailing arguments. For example, print is a common variadic function.

Here’s a function that will take an arbitrary number of ints as arguments.

def sum(*nums):
    print(nums, " ")
    total = 0
    for num in nums:
        total += num
    print(total)

Within the function, the type of nums is equivalent to tuple[int, ...]. We can call len(nums), iterate over it with a for loop, etc.

def main():
    sum(1, 2)
    sum(1, 2, 3)
    nums = [1, 2, 3, 4]
    sum(*nums)

if __name__ == "__main__":
    main()

Variadic functions can be called in the usual way with individual arguments.

If you already have multiple args in a list, apply them to a variadic function using *args like this.

nums = [1, 2, 3, 4]
sum(*nums)

To run the code, save it into a file for instance variadic_functions.py and run it using Python.

$ python variadic_functions.py
(1, 2)  
3
(1, 2, 3)  
6
(1, 2, 3, 4)  
10

Another key aspect of functions in Python is their ability to form closures, which we’ll look at next.

Next example: Closures.