Doubt about funs
Richard Carlsson
richardc@REDACTED
Tue Feb 20 18:48:47 CET 2001
> "We can also refer a function defined in a different module with
> the following syntax:
>
> F = {Module,FunctionName} "
Yes, it is true that you can (still) use tuples {Module, FunctionName} in
this manner, but it is a relic of early Erlang implementations and I
strongly recommend that they are not used in new code. If you need to pass
around a functional value to call a particular function in a particular
module, the following is much better:
F = fun (X1, ..., Xn) -> m:f(X1, ..., Xn) end
Why?
1), it is apparent that `m' is the target of a call (so e.g. tools like
`xref' can know about it, and you can easily grep for `m:' in your source
code. In general, avoid passing around module names as data. (For the same
reason, it is better to use spawn/1 and spawn/2 than the old spawn/3 and
spawn/4, if possible. Avoid `apply/3'.)
2) The `fun ... end' value is a _real_ functional value, and has a
well-defined arity.
3) It is more efficient: a static remote-call `m:f(...)' is a relatively
fast jump in modern (post-JAM) Erlang implementations, and applications of
fun-expressions are also quite efficient nowadays, while the {M, F} call
is basically executed by calling `erlang:apply(M, F, ArgList)' which is
much slower.
/Richard Carlsson
Richard Carlsson (richardc@REDACTED) (This space intentionally left blank.)
E-mail: Richard.Carlsson@REDACTED WWW: http://www.csd.uu.se/~richardc/
More information about the erlang-questions
mailing list