[erlang-questions] Functions with same name and varying arity using apply
Thu Jan 20 03:44:59 CET 2011
On Wed, Jan 19, 2011 at 18:31, Dirk Scharff <> wrote:
> I don't get what you want to do.
> From your example I assume that you want to apply a function (in your case addition) to each element of a list?
> You could to the same calculation as follows:
> lists:map(fun(X)->lists:sum(X) end,[,[2,3]]).
Sorry, I could have been more clear; I'm very early in the process of
learning Erlang and was writing my first "real" program when I
encountered this. Basically, I want to dynamically apply functions
which I've defined inside a module, which have the same name but take
different numbers of arguments. If possible, I want to do it without
exporting those "helper" functions (in this case foo/1 and foo/2).
Perhaps a better example would be if foo/2 accepted a list of options
that affected its behaviour, and foo/1 is just calling foo/2 with an
empty option list:
foo(A) -> foo(A, ).
foo(A, Options) ->
case lists:member(double, Options) of
true -> A * 2;
false -> A
bar(_, ) -> ;
bar(F, [X|Xs]) -> [apply(test, F, X) | bar(F, Xs)].
With this method, foo/1 and foo/2 have to be exported due to how
apply/3 works (I assume; that's what the documentation says, and it
fails if you don't export them). If I try using apply/2 then that
takes a function, rather than an atom, so I have to do something like:
bar(fun foo/1, [, [2, [double]]]) % from inside the module
Which is not a solution because I have to declare up front whether to
use foo/1 or foo/2, the opposite of what I'm trying to accomplish. So
I was wondering if there was another approach to make it work.
The context of discovering this is that in my program I receive the
arguments to foo (in my example: both  and [2, [double]]) from the
user by way of reading terms (I think that's the right word; I'm
reading a list of atoms and tuples and such from a file and then using
them to direct what the program does, like a very simple specification
of commands; like what one does in Lisp reading a sexp). To make it
easier, rather than forcing the user to specify an empty options list
every time there are no specific options, I allow one to be present or
absent. For this present situation, I could just transform the input
to add an empty options list when none is present, but since this is a
more general problem, I wanted to see if it was possible.
Taylor C. Venable
More information about the erlang-questions