Trivia — Pattern Matching for Common Lisp
Table of Contents
Definition
trivia is a Common Lisp pattern-matching library. It provides match and
ematch macros that dispatch on the structure and type of a value, binding
sub-components to names in the matched branch.
Online documentation: github.com/guicho271828/trivia
Forms Used in Tolk
match
(match value
(pattern₁ body₁)
(pattern₂ body₂)
(_ fallthrough-body))
Returns nil if no pattern matches (the _ catch-all prevents this).
ematch (exhaustive match)
(ematch value
(pattern₁ body₁)
(pattern₂ body₂))
Like match, but signals a trivia:match-error if no pattern matches.
Tolk uses ematch throughout to get an error rather than silent nil on
unrecognised input:
(defmethod parse (sexp)
(ematch sexp
((type number) (make-instance 'num :n sexp))
(`(+ ,l ,r) (make-instance 'plus :l (parse l) :r (parse r)))
(`(* ,l ,r) (make-instance 'mult :l (parse l) :r (parse r)))))
Patterns used in tolk
(type number)- Matches any value that satisfies
(typep value 'number). `(+ ,l ,r)- Quasiquote pattern (requires
fare-quasiquoteextension, see fare-quasiquote). Matches a three-element list whose first element is the symbol+, binding the second and third tolandr. `(* ,l ,r)- Same for multiplication.
defmethod-bind and trivia
defmethod-bind uses bind from metabang-bind rather than trivia directly.
Pattern matching in tolk's parsers uses ematch; method dispatch on AST node
type uses CLOS (no trivia needed there).
Loading
(ql:quickload :trivia) ; base
(ql:quickload :trivia.quasiquote) ; quasiquote patterns (also loads fare-quasiquote)
Related
- Fare-quasiquote — quasiquote pattern extension for trivia
- Metabang-bind — slot binding used alongside trivia in tolk
- Tolk — uses trivia for parsing
- Wikipedia: Pattern Matching