Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable length of function argument list in Erlang

Tags:

erlang

Is it possible to define function with argument list of variable length?

I know I can write just:

function() -> function([]).
function(X) when not is_list(X) -> function([X]);
function(X) -> do_something_with_arguments(X).

But I want to avoid this technique.

like image 367
Dawid Avatar asked Dec 07 '09 00:12

Dawid


People also ask

What is a variable length argument list?

Variable-length argument lists, makes it possible to write a method that accepts any number of arguments when it is called. For example, suppose we need to write a method named sum that can accept any number of int values and then return the sum of those values.

What is variable length argument in function?

A variable-length argument is a feature that allows a function to receive any number of arguments. There are situations where a function handles a variable number of arguments according to requirements, such as: Sum of given numbers. Minimum of given numbers and many more.

What are variable length arguments give an example?

Variable-length arguments, abbreviated as varargs, are defined as arguments that can also accept an unlimited amount of data as input. The developer doesn't have to wrap the data in a list or any other sequence while using them. Let's understand the concept with the help of an example.

Which operator is used to define variable length arguments?

For that we have to use ellipsis (…). Similarly for macros, we can use variable length arguments. Here also we have to include ellipsis, The '__VA_ARGS__' is used to handle variable length arguments. Concatenation operator '##' is used to concatenate the variable arguments.


2 Answers

One way to do it is to pass all arguments in a list:

function(ListOfParameters)

and then you can iterate over the said ListOfParameters. This way, you can have your function declaration be able to accept any number of "parameters", just add more terms to the declaration... but I am not sure that's what you were hoping. Are you thinking along the lines of a C vararg parameter list? In the positive case, read the next paragraph.

You have to remember that Erlang is based on pattern matching. The arguments in the function "declaration" serve as matching pattern when a function is invoked. You'll have to leave aside your "procedural programming" mindset in order to fully harness Erlang's power.

like image 91
jldupont Avatar answered Oct 30 '22 16:10

jldupont


To be much more explicit than @jldupont: No!

It is not that it has just not been implemented, but in Erlang functions with the same name but different number of arguments are considered to be different functions so it cannot be added.

like image 37
rvirding Avatar answered Oct 30 '22 17:10

rvirding