erlang

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


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?


Solution

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