Chuyển đến nội dung

Bài 7 · Language Basics

Operators, Comparison and Booleans

Learn Erlang's comparison, boolean and bitwise operators, the difference between == and =:=, short-circuit andalso/orelse, and how terms are ordered.

Operators combine values into new values. Erlang's set is small, but a few of its choices surprise newcomers: =:= versus ==, =/= for "not equal" and andalso for short-circuit logic. This lesson covers all of them, plus the rule for comparing values of different types.

Comparison operators

Operator Meaning
== Equal (compares numbers by value)
/= Not equal
=:= Exactly equal (type and value)
=/= Not exactly equal
<, > Less than, greater than
=< Less than or equal
>= Greater than or equal

Notice the oddities: "less or equal" is =<, written with the arrow shape reversed, and <= is something else entirely (it appears in binary comprehensions). "Not equal" is /=, not !=.

ERLANG
1> 5 == 5.0.
true
2> 5 =:= 5.0.
false
3> 5 /= 5.0.
false
4> 5 =/= 5.0.
true
5> 3 =< 3.
true

The difference between == and =:= matters only for integers versus floats. In practice, prefer =:= when you want precision, and use == when 1 and 1.0 should count as the same.

Boolean operators

ERLANG
1> true and false.
false
2> true or false.
true
3> true xor true.
false
4> not true.
false

and, or, xor and not work only on the atoms true and false. Anything else raises a badarg error.

Short-circuit: andalso and orelse

and and or evaluate both sides. andalso and orelse stop as soon as the answer is known:

ERLANG
1> false andalso (1/0 > 1).
false
2> true orelse (1/0 > 1).
true
3> false and (1/0 > 1).
** exception error: an error occurred when evaluating an arithmetic expression

Use the short-circuit forms in almost all code, especially to guard a risky test with a safe one: is_list(X) andalso length(X) > 3. A subtle difference: the right operand of andalso and orelse may be any term in a tail position, but the left side must be a boolean.

Term ordering across types

Erlang can compare any two terms, even of different types. The order is:

TEXT
number < atom < reference < fun < port < pid < tuple < map < nil < list < bitstring
ERLANG
1> 1 < a.
true
2> {1, 2} < [1, 2].
true
3> a < b.
true
4> "abc" < "abd".
true

Atoms compare alphabetically, tuples compare first by size and then element by element, and lists compare element by element. This makes sorting mixed data well-defined: lists:sort([b, 3, a, 1.5, {x}]) gives [1.5,3,a,b,{x}].

Arithmetic and bitwise operators

You met + - * / div rem already. For bits Erlang uses words:

Operator Meaning Example Result
band Bitwise AND 12 band 10 8
bor Bitwise OR 12 bor 10 14
bxor Bitwise XOR 12 bxor 10 6
bnot Bitwise NOT bnot 0 -1
bsl Shift left 1 bsl 4 16
bsr Shift right 256 bsr 2 64

List operators: ++ and --

ERLANG
1> [1, 2] ++ [3, 4].
[1,2,3,4]
2> [1, 2, 3, 2] -- [2].
[1,3,2]
3> "ab" ++ "cd".
"abcd"

++ appends two lists, and -- removes the first occurrence of each element on the right. Because lists are linked, A ++ B copies A but shares B, so put the shorter list on the left, and avoid repeated Acc ++ [X] in loops, which is slow (quadratic).

Operator precedence

From highest to lowest, roughly:

  1. # (record/map access), : (module call)
  2. unary + - bnot not
  3. / * div rem band and
  4. + - bor bxor bsl bsr or xor
  5. ++ -- (right associative)
  6. == /= =< < >= > =:= =/=
  7. andalso
  8. orelse
  9. = (match, right associative) and ! (send)
  10. catch

When in doubt, add parentheses. X > 0 andalso Y > 0 works as you expect because comparison binds tighter than andalso.

Stand-ins in JavaScript

These snippets mirror Erlang rules in JavaScript. They are not Erlang.

JS Stand-in: == versus =:= (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: ordering of mixed terms (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does 5 == 5.0 return in Erlang?

    == compares numbers by value, so 5 and 5.0 are equal. 5 =:= 5.0 is false.
  2. 2. Which operator means 'less than or equal'?

    Erlang writes it =<. The sequence <= belongs to binary comprehensions.
  3. 3. Why prefer andalso over and?

    andalso and orelse short-circuit, so a risky right-hand side may never run.
  4. 4. How do you write 'not equal' (value comparison)?

    /= is not equal; =/= is not exactly equal.

Summary

  • ==//= compare by value; =:=/=/= also compare the type of number.
  • Less or equal is =<; greater or equal is >=.
  • and/or evaluate both sides; andalso/orelse short-circuit and are usually what you want.
  • Bitwise operators are words: band, bor, bxor, bnot, bsl, bsr.
  • Any two terms can be compared: numbers come before atoms, tuples, lists and so on.

Next: Printing and Strings

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.