[erlang-questions] clarify: How are functions assigned to variables compared in Erlang?
Tim Bates
tim@REDACTED
Thu Dec 13 11:07:26 CET 2007
Juan Jose Comellas wrote:
> 1> F1 = fun(X) -> X + 1 end.
> #Fun<erl_eval.6.49591080>
>
> 2> F2 = fun(X) -> X + 1 end.
> #Fun<erl_eval.6.49591080>
>
> 3> F3 = fun(X) -> X + 2 end.
> #Fun<erl_eval.6.49591080>
>
> 4> F1 =:= F2.
> true
>
> 5> F1 =:= F3.
> false
Bjorn Gustavsson wrote:
> The Erlang VM does not compare the code of the functions; it compares
> unique identifiers.
>
> It also compares the environment of the funs.
Juan,
Note that in your example, since you are building the funs from the
shell, and they all have the same arity, the unique identifiers in all
three are the same - the actual code is stored in the environment of the
fun[1]. This is why F1 and F2 compare equal - in this particular case
only, it does actually compare the code. If I were to do the same thing
in a module:
-module(fun_test).
-compile(export_all).
fun1() ->
fun(X) -> X + 1 end.
fun2() ->
fun(X) -> X + 1 end.
fun3() ->
fun(X) -> X + 2 end.
compare_funs() ->
F1A = fun1(),
F1B = fun1(),
F2 = fun2(),
F3 = fun3(),
[F1A =:= F1B,
F1A =:= F2,
F1A =:= F3].
I get different results:
Eshell V5.5.4 (abort with ^G)
1> c(fun_test).
{ok,fun_test}
2> fun_test:fun1().
#Fun<fun_test.0.20406117>
3> fun_test:fun2().
#Fun<fun_test.1.86108340>
4> fun_test:fun3().
#Fun<fun_test.2.109923222>
5> fun_test:compare_funs().
[true,false,false]
Tim.
[1] See erl_eval:expr/5, the section with the comment as follows:
%% This is a really ugly hack!
--
Tim Bates
tim@REDACTED
More information about the erlang-questions
mailing list