Language
Pattern Matching
Tea uses `case` patterns in catch blocks and match-style control flow over values and variants.
Pattern matching lets you branch on values and variants with a sequence of case arms. It is useful both in ordinary control flow and in error recovery.
Match a value directly
Use match when you want to inspect one value and choose a result from several cases. Literal patterns match exact values, and _ acts as the fallback arm.
const status = 200
const label = match status
case 200 => "ok"
case 404 => "not found"
case _ => "unexpected"
end
@println(label)Pattern matching in error recovery
Pattern matching is especially useful in catch blocks, where case is ... lets you branch on specific error variants and recover with different values.
error DataError {
Missing(path: String)
Permission
}
def describe(path: String) -> String
try read(path) catch err
case is DataError.Missing
`missing:${err.path}`
case is DataError.Permission
"denied"
case _
"unexpected"
end
endPattern forms
- Use literal patterns such as
case 200for exact values. - Use
case is Type.Variantto match specific typed variants. - Use
_as the final fallback when no earlier pattern matches.