← Back to lesson 28: Parse one real line

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 input, split once, normalize the level, and return a tagged result.

Parse valid, empty, and malformed lines without raising.

Run this first

Run it once, change one input, and compare the new result.

Original full example
# Parse without letting outside text leak inward
parse = fn line ->
  case String.split(String.trim(line), ~r/\s+/, parts: 2) do
    [""] -> :skip
    [level, message] when level in ["INFO", "WARN"] -> {:ok, {String.to_atom(String.downcase(level)), message}}
    _ -> {:error, :invalid_line}
  end
end

{parse.(" INFO ready "), parse.(""), parse.("BROKEN")}

The three results are {:ok, {:info, "ready"}}, :skip, and {:error, :invalid_line}.

Steps for the full example

  1. Read String.split(..., parts: 2): Split only the level from the remaining message.
  2. Read String.downcase/1: Normalize the level text.
  3. 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 equivalent spellings to one internal value.

Symbols and terms
String.split(..., parts: 2)
Split only the level from the remaining message.
String.downcase/1
Normalize the level text.
{:error, reason}
Return malformed input as data.
parser boundary
A parser turns outside text into a small internal data shape.
normalization
Normalization converts equivalent spellings to one internal value.
total result
Every input returns one documented result instead of falling through.

Original full exercise

Accept ERROR disk as an error-level record.

Exercise starter
when level in ["INFO", "WARN", ____]

Add "ERROR".

Show hint

Keep external levels as strings in the guard.

Show original answer
Reference answer
when level in ["INFO", "WARN", "ERROR"]
Why split with parts: 2?

The message may contain spaces; only the first boundary belongs to the level.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references