What is the difference between == and =:= in Erlang when used with terms in general?

蓝咒 提交于 2019-12-30 03:44:06

问题


Apart from the fact that =:= prevents unwanted integer casts:

1> 1=:=1.0.
false

What is the advantage of using =:= with terms in general?

Better performance?


回答1:


The biggest advantage of =:= is it returns true only for same terms in the same way as pattern matching. So you can be sure they are same. 1 and 1 are same terms and 1 with 1.0 are not. That's it. If you write function like foo(A, B) when A =:= B -> A. and bar(A, B) when A =:= B -> B. they will behave same. If you use == it will not be same functions. It simply prevents surprise. For example, if you make some key/value storage it would not be right if you store value with key 1 and then get this value if ask for key 1.0. And yes, there is a little bit performance penalty with == but least astonishment is far more important. Just use =:= and =/= when it is your intent to compare same terms. Use == and /= only if it is your intent to compare numbers.




回答2:


*Eshell V5.9.3.1  (abort with ^G)   
1> 1.0==1.   
true   
2> 1.0=:=1.  
false  

When we go with == it will transfer both elements into the same format to match. With =:= it does not happen – when the two elements are same-type and same-value it will return true.



来源:https://stackoverflow.com/questions/9790815/what-is-the-difference-between-and-in-erlang-when-used-with-terms-in-gene

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!