Elixir basics · Lesson 27 (open contents)
Parse one real line
Trim input, split once, normalize the level, and return a tagged result.
Run this first
Run it once, change one input, and compare the new result.
# 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}.
Read from the first line down
- Read
String.split(..., parts: 2): Split only the level from the remaining message. - Read
String.downcase/1: Normalize the level text. - Read
{:error, reason}: Return malformed input as data.
Symbols are not secret signs
String.split(..., parts: 2)Split only the level from the remaining message.
String.downcase/1Normalize the level text.
{:error, reason}Return malformed input as data.
Match each name to its meaning
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.
Why these forms are useful
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.
Close the answer and try
Accept ERROR disk as an error-level record.
when level in ["INFO", "WARN", ____]Target result: Add "ERROR".
Stuck? Read one hint
Keep external levels as strings in the guard.
After you run it, see one answer
when level in ["INFO", "WARN", "ERROR"]Think about it: Why split with `parts: 2`?
The message may contain spaces; only the first boundary belongs to the level.
Remember these three lines
- 1
Normalize at the boundary.
- 2
Return tagged failures.
- 3
Do not create atoms from unlimited outside text.