Parse one real line: full examples and further reading
The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.
The original English project below is a log cleaner. The current notebooks use the same file-statistics project as the Chinese route. These preserved examples show another application of the concepts; their inputs and expected outputs belong to the log cleaner.
Trim a binary, split once, normalize its level, and return a tagged result.
Parse valid, empty, and malformed log lines without crashing.
Run this first
Run it once, change one input, and compare the new result.
%% Keep outside text at one boundary
Parse = fun(Line) ->
case binary:split(string:trim(Line), <<" ">>, [trim]) of
[] -> skip;
[<<"INFO">>, Message] -> {ok, {info, Message}};
[<<"WARN">>, Message] -> {ok, {warn, Message}};
_ -> {error, invalid_line}
end
end,
{Parse(<<"INFO ready">>), Parse(<<>>), Parse(<<"BROKEN">>)}.The results show one accepted record, skip, and {error,invalid_line}.
Steps for the full example
- Read
binary:split/3: Split the level from the remaining message. - Read
string:trim/1: Remove surrounding whitespace. - Read
{error, Reason}: Return malformed input as data.
Original lesson notes
Run the example first. Predict one result, then change one input and run it again.
A parser turns outside text into a small internal data shape.
Normalization converts accepted spellings to one internal value.
Symbols and terms
binary:split/3- Split the level from the remaining message.
string:trim/1- Remove surrounding whitespace.
{error, Reason}- Return malformed input as data.
- parser boundary
- A parser turns outside text into a small internal data shape.
- normalization
- Normalization converts accepted spellings to one internal value.
- complete result
- Every input returns one documented result instead of falling through.
Original full exercise
Accept an ERROR line.
[<<"ERROR">>, Message] -> {ok, {____, Message}};Use the atom error.
Show hint
The internal level is a known atom.
Show original answer
[<<"ERROR">>, Message] -> {ok, {error, Message}};Why avoid creating atoms from arbitrary input?
Atoms are not garbage-collected in the usual way; unlimited outside values can exhaust the atom table.
Original lesson takeaways
- Normalize at the boundary.
- Return tagged failures.
- Convert only known text to atoms.