tags:

views:

201

answers:

2

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.

+5  A: 

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.

jldupont
First part of Your answer is the same as technique as I mentioned, I thought about something similar to C so I read second part so now I have to fall back to my first solution. Thanks for response!
Dejw
My pleasure! Have fun with Erlang!
jldupont
+2  A: 

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.

rvirding