Function equality/ordering in erlang

What does it mean to compare functions in Erlang with the operators =:= , == , < , > , =< , >= ? I was playing around with the interpreter and got these results:

Eshell V5.9.2  (abort with ^G)
1> X = fun() -> {} end.
#Fun<erl_eval.20.82930912>
2> Y = fun() -> {} end.
#Fun<erl_eval.20.82930912>
3> 
3> {X == X, X =:= X}.
{true,true}
4> {X >= X, X =< X}.
{true,true}
5> {X > X, X < X}.
{false,false}
6> 
6> {X == Y, X =:= Y}.
{true,true}
7> {X >= Y, X =< Y}.
{true,true}
8> {X > Y, X < Y}.
{false,false}

This makes sense. It looks like it's comparing the abstract syntax tree of the two functions.

But in this session X and Y are defined the same once again but are different, also now X<Y ?

Eshell V5.9.2  (abort with ^G)
1> X = fun() -> {} end.
#Fun<erl_eval.20.82930912>
2> 
2> {X == X, X =:= X}.
{true,true}
3> {X >= X, X =< X}.
{true,true}
4> {X > X, X < X}.
{false,false}
5> 
5> Y = fun() -> {} end.
#Fun<erl_eval.20.82930912>
6> 
6> {X == Y, X =:= Y}.
{false,false}
7> {X >= Y, X =< Y}.
{false,true}
8> {X > Y, X < Y}.
{false,true}

So it looks like it's not comparing the AST or any sort of unique references. Maybe it is comparing references, just some optimization is happening and X and Y get bound to the same reference? If there is some explanation for this, what happens across different VMs or different nodes?


The difference between the 2 evaluation in the shell comes from the blank line 6>. if you have a look at the fun using the function erlang:fun_info/1, you will see that in that case, the clause is stored with a different number (ie 2 instead of 1).

If you enter again the definition of Y (without a blank line) you will get a bad match, if you enter a blank line before, it is OK.

I think that this is a side effect of using the shell, but that the behavior is consistent within a program. Of course the meaning of > or < is not obvious for a fun, but == yes. A nice thing also is that the order of Erlang term is defined, so it is possible to sort a list of any term with predictable behavior:

number < atom < reference < fun < port < pid < tuple < list < bit string
链接地址: http://www.djcxy.com/p/11356.html

上一篇: 组件:JSON路径声明

下一篇: erlang中的函数相等/排序