Erlang basics · Lesson 03 (open contents)
Tell two kinds of text apart
Understand charlists, binaries, and UTF-8 text.
Text can look alike while having a different shape
Here =:= performs a strict equality comparison.
%% Double quotes make a charlist by default
"cat" =:= [99, 97, 116].
%% Double angle brackets make a binary
is_binary(<<"cat">>).
%% A non-ASCII binary states its UTF-8 encoding
byte_size(<<"café"/utf8>>).- The charlist comparison returns
true. is_binary(<<"cat">>)returnstrue.byte_size(<<"café"/utf8>>)returns5: five bytes, not four written characters.
Read from the first line down
"cat"looks like text in the shell, but it equals the integer list[99, 97, 116].<<"cat">>is a binary. It is not equal to the charlist"cat".byte_size(<<"café"/utf8>>)counts bytes. The letterétakes two UTF-8 bytes.
Symbols are not secret signs
"cat"A charlist by default, which means a list of integers.
<<"cat">>The double angle brackets wrap a binary.
/utf8Encode the text before it as UTF-8 inside the binary.
=:=Strictly compare whether the values on both sides are the same.
Match each name to its meaning
charlist
A list of character numbers. "cat" and [99, 97, 116] are the same value.
binary
A sequence of bytes written as <<...>>. Binaries are common for text, files, and network data.
UTF-8
An encoding rule that turns Unicode text into bytes.
Why these forms are useful
Erlang has no separate string type. "cat" in double quotes is a list of character numbers by default. This is called a charlist.
<<"cat">> is a binary. Many network protocols, files, and modern Erlang interfaces use binaries for text.
For a non-ASCII character inside a binary, add /utf8, as in <<"café"/utf8>>. This tells Erlang exactly how to encode the text.
Close the answer and try
Write café as a binary, then check it with is_binary(...).
%% Give the UTF-8 binary directly to the check
is_binary(<<____/utf8>>).Target result: The result should be true.
Stuck? Read one hint
Write the text in double quotes inside the blank.
After you run it, see one answer
%% /utf8 states how to encode the non-ASCII letter
is_binary(<<"café"/utf8>>).Think about it: Are `"cat"` and `<<"cat">>` the same value?
No. The first is a charlist by default. The second is a binary. They can show similar text but have different types.
Remember these three lines
- 1
Erlang has no separate string type.
- 2
Double quotes make a charlist by default.
<<>>makes a binary. - 3
Use
/utf8when a binary literal contains non-ASCII text.