Michael J. Fox playing Johnny B. Goode — Back to the Future (1985)

The Many Strings of Erlang

Most languages have one or maybe two types/classes to manage strings. But not Erlang. In Erlang we have, well…

Strings

1> String = “this is a string”.

“this is a string”

2> StringToo = [$t, $h, $i, $s, $,, $\s, $t, $o, $o].

“this, too”

Strings are the original ones, just lists of integers with some syntactic sugar that are pretty printed as characters.

Binaries

3> Binary = <<”this is a binary”>>.

<<”this is a binary”>>

4> BinaryToo = <<$t, $h, $i, $s, $,, “ too”>>.

<<”this, too”>>

Binaries are sequences of bytes. There is also syntactic sugar for this and you can read them.

IO Lists

5> IOList = [“this”, <<” is “>>, [“an”, <<” IO “>>] | <<”List”>>].

[“this”,<<” is “>>,[“an”,<<” IO “>>]|<<”List”>>]

6> io:format(“~s~n”, [IOList]).

this is an IO List

Binaries and Strings were fine, but more often than not you find yourself converting and concatenating them a lot. To optimise that there is a more relaxed way to build strings that can be interpreted by functions in the io module (and many others): IOLists. IOLists are (maybe improper) lists of strings, binaries, chars or IOLists. But, as you can see, since IOLists are lists, a single binary is not a valid IOList, although it might work well in the same scenarios. To accommodate for that fact, we have a broader type…

IO Data

7> IOData = [“this”, <<” is “>>, [“IO”] | <<” data”>>].

[“this”,<<” is “>>,[“IO”]|<<” data”>>]

8> IODataToo = <<”This is IOData, too”>>.

<<”This is IOData, too”>>

9> io:format(“~s~n”, [IOData]).

this is IO data

ok

IOData is basically just IOList or binary.

Type Specs

So, we have at least 4 different types of strings here, but luckily, each one of them has its own type specified by OTP. If you dig through the Erlang docs you’ll find these are all built-in types, defined as follows