Arity of funs
Matthias.Lang@REDACTED
Matthias.Lang@REDACTED
Thu Mar 16 09:49:58 CET 2000
Just to close off this topic...
It caught my eye that the size of a fun depends on its 'complexity':
3> term_to_binary(fun() -> ok end).
#Bin<158>
4> term_to_binary(fun(a,b,c,d) -> {p,q,r,s} end).
#Bin<285>
That led me to suspect the fun carries BEAM code around with it. To
test that, I tried sending the fun around. For instance you can write
the binary to disk, start a new node, load the binary, use
binary_to_term and presto, you can execute the fun. Similarly you can
send it to another node. Therefore it must be carrying the code around.
Björn cleared up a couple of things. Firstly, funs defined in the
shell are special because they're not part of a module in the same way
compiled fun code is. Only shell funs carry the code around.
Secondly, the code being carried around isn't BEAM, it's a dump of the
compiler's parse tree, a lot like Sun's implementation of C++
templates (do they still do it that way?).
Matthias
--------------------
P.S: here's the besserwisser code. It, of course, works just like Björn
and Tony guessed.
-module(besserwisser).
-export([arity/1]).
arity(F) when function(F) ->
loop(F, []).
loop(F, Args) ->
case catch (apply(F, Args)) of
{'EXIT', {badarity, _}} -> loop(F, [0|Args]);
_ -> length(Args)
end.
It only has side effects if the code you pass it has side effects,
which I think is completely fair ;-)
More information about the erlang-questions
mailing list