[erlang-questions] Functions with same name and varying arity using apply
Fri Jan 21 04:46:44 CET 2011
On Wed, Jan 19, 2011 at 22:51, Steve Vinoski <> wrote:
> On Wed, Jan 19, 2011 at 9:44 PM, Taylor Venable <> wrote:
>> 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 you don't export them, the compiler will think they're unused and
> won't include them in the generated beam file, in which case they
> obviously won't be around to call by any means.
I'm trying to call them from inside the module; foo/1 and foo/2 are
helper functions inside the module that are only to be used within the
>> 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.
> You might consider just always passing a single list argument to foo,
> so there's just one to export. It could work like this:
Yeah, doing some searching seems to indicate this is the common way of
doing variadic functions in Erlang. No point in trying to do something
complicated when this method will 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
> Using file:consult/1, I hope?
>> 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).
> Another option along the Lisp reader line would be to read the user's
> terms, and based on those terms first generate "code as data" in
> Abstract Format as a set of terms, then compile it and load the
> resulting beam on the fly, and finally invoke one of the newly-loaded
> functions. Look up Abstract Format in the erts manual and also see the
> compile module and the beam_lib module. Whether it's worth it to go to
> this extent depends on how often the code would be invoked -- if
> you're writing some sort of DSL that's read once and then invoked
> numerous times, this approach could be worth it.
That's interesting, and a lot for me to digest there. This is just a
small program mostly for learning purposes, so I'm going to keep it as
simple as I can, but that is something that will definitely merit
curious perusal later.
Taylor C. Venable
More information about the erlang-questions