Variadic Functions in Erlang

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

-module(variadic_functions).
-export([sum/1, main/0]).

sum(Numbers) ->
    io:format("~p ", [Numbers]),
    Total = lists:sum(Numbers),
    io:format("~p~n", [Total]).

main() ->
    %% Variadic functions can be called in the usual way with individual arguments
    sum([1, 2]),
    sum([1, 2, 3]),

    %% If you already have multiple args in a list, apply them to a variadic function using the list directly
    Numbers = [1, 2, 3, 4],
    sum(Numbers).

To run the program, compile the code into a .beam file and use erl to execute it.

$ erlc variadic_functions.erl
$ erl -noshell -s variadic_functions main -s init stop
[1,2] 3
[1,2,3] 6
[1,2,3,4] 10

In Erlang, we achieve similar functionality using lists and pattern matching. The sum/1 function collects all arguments in a list and calculates the total sum using lists:sum/1. The main/0 function demonstrates calling the sum/1 function with few example cases.