ok and error tuples in Erlang
{ok, Value} and {error, Reason}: the convention every API keeps.
%% {ok, Value} and {error, Reason}: the convention every API keeps.
lookup("5560199") -> {ok, "Maud's desk"};
lookup("5560142") -> {ok, "front counter"};
lookup(_) -> {error, unlisted}.
main(_) ->
Numbers = ["5560199", "5550000", "5560142"],
[case lookup(N) of
{ok, Where} ->
io:format("~s rings ~s~n", [N, Where]);
{error, Reason} ->
io:format("~s failed: ~p~n", [N, Reason])
end || N <- Numbers],
ok.
How it works
- Success and failure are just tuples to match on.
case lookup(N) ofbranches on the tag.- No exceptions needed for expected failures.
Keywords and builtins used here
caseendformatlookupmainof
The run, in numbers
- Lines
- 14
- Characters to type
- 403
- Tokens
- 134
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 134 seconds.
Step 1 of 2 in Errors as data, step 23 of 31 in Language basics.