The standard library tour
Most of an Erlang program is a call into the standard library, and the same forty functions do most of the work. This lesson walks through the ones the earlier chapters used, one module at a time, so the reader knows where to look before writing a helper that already exists.
Lists, maps and strings
lists works on proper lists: seq/2 builds a range, zip/2 pairs two lists, sum/1 adds, and sort/1 orders by the term order. maps owns the map: keys/1, values/1, merge/2 and get/2. string works on binaries and charlists, and binary on raw bytes; the two split functions below take the pattern as a binary, not a string:
stdlib.erl
-module(stdlib). -export([main/0]). main() -> io:format("~p~n", [lists:seq(1, 5)]), io:format("~p~n", [lists:zip([a, b], [1, 2])]), io:format("~p~n", [lists:sum([1, 2, 3])]), io:format("~p~n", [lists:sort(maps:keys(#{b => 2, a => 1}))]), io:format("~p~n", [string:split(<<"a,b,c">>, <<",">>, all)]), io:format("~p~n", [binary:split(<<"a:b">>, <<":">>)]), io:format("~s~n", [io_lib:format("~p of ~p", [1, 2])]).
erlc stdlib.erl
erl -noshell -eval 'stdlib:main(), halt().'
[1,2,3,4,5] [{a,1},{b,2}] 6 [a,b] [<<"a">>,<<"b">>,<<"c">>] [<<"a">>,<<"b">>] 1 of 2
maps:keys/1 does not promise an order, so the program sorts the answer before printing it; a page that printed the raw keys would print a different line on another release. io_lib:format/2 answers the text as data, which is why the last line uses ~s to print it; the output lesson covers the directives.
Property lists
proplists reads the keyword list of the keywords lesson. It answers the first value for a key, a default when the key is absent, and every value of a repeated key. lists:keyfind/3 is the plain list function underneath, and it answers the whole pair or false:
prop.erl
-module(prop). -export([main/0]). main() -> Options = [{retries, 3}, {mode, fast}, {tag, normal}, {tag, alt}], io:format("~p~n", [proplists:get_value(retries, Options)]), io:format("~p~n", [proplists:get_value(timeout, Options, 5000)]), io:format("~p~n", [proplists:get_all_values(tag, Options)]), io:format("~p~n", [lists:keyfind(mode, 1, Options)]).
erlc prop.erl
erl -noshell -eval 'prop:main(), halt().'
3 5000 [normal,alt] {mode,fast}
The two modules differ in what a miss answers: get_value/2 answers undefined, keyfind/3 answers false, and maps:get/2 raises. The next section is about that last one.
The missing key
maps:get/2 demands the key and raises {badkey, Key} when it is absent. That is the right default for a key the program requires, and the wrong one for an optional field. The module below turns the raise into a value and compares it with maps:find/2, which answers {ok, Value} or error:
missing.erl
-module(missing). -export([main/0, age/1]). age(Map) -> Result = try maps:get(age, Map) of Value -> {ok, Value} catch error:{badkey, Key} -> {error, {missing, Key}} end, Result. main() -> io:format("~p~n", [age(#{name => <<"Ada">>})]), io:format("~p~n", [maps:find(age, #{name => <<"Ada">>})]).
erlc missing.erl
erl -noshell -eval 'missing:main(), halt().'
{error,{missing,age}} error
The catch clause could be the catch-all of the error handling lesson, but it names the class and the reason, so a map that is not a map still crashes. Prefer maps:find/2 or maps:get/3 when the key is optional; the raise is for the key that must be there.
Which function
Three habits save a helper function. For a list, look in lists first, then in string if it is text, then in binary if it is raw bytes. For a map, maps has the operation; a keyword list is proplists. For formatting, io_lib:format/2 builds text and io:format/2 prints it. The maps in depth lesson and the lists lesson go deeper into the two that a program uses most.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which module builds the list
[1,2,3,4,5]?Answer
lists:seq/2lists:seq(1, 5)answers the five integers, endpoints included. -
What does
lists:zip([a, b], [1, 2])answer?Answer
[{a,1},{b,2}]zip/2pairs the items of the two lists into two-item tuples. -
Why does the program sort
maps:keys/1?Answer
maps:keys/1does not promise an orderA map has no promised key order, so a sorted answer is the same on every run.
-
What does
proplists:get_value/2answer for a missing key?Answer
undefinedWithout a default,
get_value/2answers the atomundefined. -
What does this module print?
-module(q1). -export([main/0]). main() -> io:format("~p~n", [lists:seq(2, 4)]).Answer
[2,3,4]seq/2includes both ends, so the list is 2, 3 and 4. -
What does this module print?
-module(q2). -export([main/0]). main() -> io:format("~p~n", [string:split(<<"a b c">>, <<" ">>, all)]).Answer
[<<"a">>,<<"b">>,<<"c">>]allsplits at every separator and keeps the parts as binaries. -
What does this module print?
-module(q3). -export([main/0]). main() -> io:format("~p~n", [proplists:get_all_values(tag, [{tag, red}, {tag, blue}])]).Answer
[red,blue]get_all_values/2collects every value of the key, in list order. -
What does this module print?
-module(q4). -export([main/0]). main() -> io:format("~p~n", [maps:find(age, #{name => "Ada"})]).Answer
errormaps:find/2answerserrorfor a missing key instead of raising. -
What does
maps:get/2do when the key is absent?Answer
Raises
{badkey, Key}The two-argument form demands the key; the three-argument form takes a default instead.
-
Which call builds text without printing it?
Answer
io_lib:format/2io_lib:format/2answers the text as data;io:format/2writes it to the group leader.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev