Tell two kinds of text apart: full examples and further reading
The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.
Understand charlists, binaries, and UTF-8 text.
Run "cat" and <<"cat">> in erl, test the binary, and build one UTF-8 binary.
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">>) returns true.
byte_size(<<"café"/utf8>>) returns 5: five bytes, not four written characters.
Steps for the full example
"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.
Original lesson notes
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.
Symbols and terms
"cat"- A charlist by default, which means a list of integers.
<<"cat">>- The double angle brackets wrap a binary.
/utf8- Encode the text before it as UTF-8 inside the binary.
=:=- Strictly compare whether the values on both sides are the same.
- 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.
Original full exercise
Write café as a binary, then check it with is_binary(...).
%% Give the UTF-8 binary directly to the check
is_binary(<<____/utf8>>).The result should be true.
Show hint
Write the text in double quotes inside the blank.
Show original answer
%% /utf8 states how to encode the non-ASCII letter
is_binary(<<"café"/utf8>>).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.
Original lesson takeaways
- Erlang has no separate string type.
- Double quotes make a charlist by default.
<<>>makes a binary. - Use
/utf8when a binary literal contains non-ASCII text.