### Define Lisp Variables and Structure Source: https://github.com/guicho271828/trivia/wiki/What-is-pattern-matching?-Benefits?.org Defines sample Lisp variables and a structure to be used in subsequent pattern matching examples. No external dependencies are required. ```lisp (defvar a1 '(:a 2 10)) (defstruct foo bar baz) (defvar a2 (make-foo :bar 2 :baz 5)) ``` -------------------------------- ### Optimization Trace Log (Lisp) Source: https://github.com/guicho271828/trivia/wiki/Benchmarking-Results.org An example trace log showing the optimization process for the Balland2006 scheme. It includes details on swapping, fusing, evaluation time, and memory consing. ```lisp -------------------- BALLAND ---------------------------------------- ; Swapping (EQL #:IT1 0), (EQL #:IT2 1) under T ; Fusing T, T Evaluation took: 11.130 seconds of real time 11.129130 seconds of total run time (11.125170 user, 0.003960 system) 99.99% CPU 33,390,657,846 processor cycles 36,464 bytes consed ; Grounding ; (((OR1 (GUARD1 (#:IT1 :IGNORABLE T ...) (TYPEP #:IT1 '(SIMPLE-VECTOR 25)) ...) ; (GUARD1 (#:IT7 :IGNORABLE T ...) (TYPEP #:IT7 '(SIMPLE-VECTOR 25)) ...) ...)) ; 1) ; Grounding ; (((OR1 (GUARD1 (#:IT73 :IGNORABLE T ...) (TYPEP #:IT73 '(SIMPLE-VECTOR 25)) ...) ; (GUARD1 (#:IT79 :IGNORABLE T ...) (TYPEP #:IT79 '(SIMPLE-VECTOR 25)) ...) ...)) ; 0) ; Fusing ; (TYPEP #:IT1 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT7 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT13 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT19 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT25 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT31 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT37 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT43 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT49 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT55 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT61 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT67 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT73 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT79 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT85 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT91 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT97 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT103 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT109 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT115 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT121 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT127 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT133 '(SIMPLE-VECTOR 25)), ; (TYPEP #:IT139 '(SIMPLE-VECTOR 25)) ``` -------------------------------- ### Lisp Nested Pattern Matching Example Source: https://github.com/guicho271828/trivia/wiki/What-is-pattern-matching?-Benefits?.org An example of nested pattern matching in Lisp using the 'match' macro. It demonstrates accessing elements within deeply nested list structures and returning a specific value. ```lisp (match '(:a (3 4) 5) ((list :a (list _ c) _) c)) ``` -------------------------------- ### Lisp Match Macro Clause for List Pattern Source: https://github.com/guicho271828/trivia/wiki/What-is-pattern-matching?-Benefits?.org Demonstrates a list pattern within the Lisp 'match' macro. This example shows matching a list of a specific length, using constant patterns, variable binding, and wildcard patterns. ```lisp (match x ((foo (bar b) (baz :a)) ...body1...) ((list :a b _) ...body2...)) ``` -------------------------------- ### Constant Pattern Matching in Optima Source: https://github.com/guicho271828/trivia/wiki/Known-Differences Demonstrates Optima's handling of constant patterns, where only immediate literals like characters, keywords, and numbers are matched. This section shows basic matching examples. ```lisp (match 1 (1 2)) => 2 (match "foo" ("foo" "bar")) => "bar" (match '(1) ('(1) 2)) => 2 ``` -------------------------------- ### Optimized Regexp Pattern Example Source: https://github.com/guicho271828/trivia/wiki/Ideas This example shows an optimized version of the regexp pattern matching where common portions are merged. This is achieved by decomposing the testing code and allowing the optimizer to identify and combine redundant checks. ```lisp (match str ((ppcre "aa(.*)" rest) (match rest ((ppcre "a([bc]*)" b-and-cs) b-and-cs) ((ppcre "(d*)" ds)))) ``` -------------------------------- ### Swapping Rule Example in Lisp Source: https://github.com/guicho271828/trivia/blob/master/balland2006/README.org Shows the Swapping optimization rule in Lisp, which reorders adjacent conditional blocks. This rule does not directly reduce the number of tests but aids in merging blocks through a strategic ordering. ```lisp IfSwapping: if(c1,i1,nop);if(c2,i2,nop)→if(c2,i2,nop);if(c1,i1,nop) IF c1⊥c2 ``` -------------------------------- ### let-match Macro Example Source: https://github.com/guicho271828/trivia/wiki/Match-and-Variants.org The `let-match` macro is a shorthand built on top of `ematch*` for performing pattern matching within a local binding context. It allows for destructuring and matching of variables directly in the `let` form. ```Common Lisp (trivia:let-match ((a 1) ;; this works but can't just do just b with current implementation (b) ((list _ c d) (list 1 2 3)) ((cons e f) '(4 . 5)) ;; trivia doesn't have a values pattern ((last (list g h) 2) (multiple-value-list (values 1 2 3 4 5 6 7)))) (list a b c d e f g h)) ;; => (1 NIL 2 3 4 5 6 7) ``` -------------------------------- ### Redundant Regexp Pattern Example Source: https://github.com/guicho271828/trivia/wiki/Ideas This example demonstrates a scenario where regexp patterns contain redundant tests that could be merged. The current implementation does not automatically merge these, leading to repeated checks. ```lisp (match str ((ppcre "aaa([bc]*)" b-and-cs) b-and-cs) ((ppcre "aa(d*)" ds))) ``` -------------------------------- ### Simple Predicate Guard Matching (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Demonstrates the 'guard' pattern, which allows arbitrary predicates to be used as matching conditions. This example checks if a number is even. ```lisp ;; Simple predicate guard (match 4 ((guard x (evenp x)) :even) (_ :odd)) ;; => :EVEN ``` -------------------------------- ### Match Hash Table Entry by Key with 'hash-table-entry' (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Introduces the 'hash-table-entry' pattern for matching a specific key-value pair in a hash table. This example retrieves the value associated with key ':a'. ```lisp ;; Hash table matching (let ((table (alexandria:plist-hash-table '(:a 1 :b 2)))) (match table ((hash-table-entry :a val) val))) ;; => 1 ``` -------------------------------- ### Interleaving Rule Example in Lisp Source: https://github.com/guicho271828/trivia/blob/master/balland2006/README.org Illustrates the Interleaving optimization rule in Lisp, which reduces conditional checks by exploiting exhaustive type partitions. If two conditions cover all possibilities for a type, one can be eliminated. ```lisp (match1 what ((guard1 it (consp it)) body1) ((guard1 it (null it)) body2)) Since `cons' and `null' are the exhaustive partition of type `list', this can be optimized into (match1 what ((guard1 it (consp it)) body1) (_ body2)) ``` -------------------------------- ### Fusion Rule Example in Lisp Source: https://github.com/guicho271828/trivia/blob/master/balland2006/README.org Demonstrates the Fusion optimization rule in Lisp, where common type checks in adjacent pattern matches are merged to reduce redundancy. This rule infers types from predicates and combines compatible checks. ```lisp (match1 what ((guard1 it (consp it) (car it) (guard1 x (= 1 x)) (cdr it) (guard1 y (null y))) body1) ((guard1 it (consp it) (car it) (guard1 x (stringp x)) (cdr it) (guard1 y (null y))) body2)) body1 has an environment where : it <-- (consp it) <-- can be infered as type `cons' : car <-- (= 1 car) <-- not inferred right now: an anonymous type e.g. #:ANON0 : cdr <-- (null y) <-- type `null' body2 has an environment where : it <-- (consp it) <-- can be infered as type `cons' : car <-- (stringp x) <-- can be infered as type `string' : cdr <-- (null y) <-- type `null' Since the two checks have type `cons' in common, the first check can be merged. In the above case, the original code is compiled into: (match what ((guard1 it (consp it) (car it) #:car (cdr it) #:cdr) (match* (#:car #:cdr) (((guard x (= 1 x)) (guard y (null y))) body1) (((guard x (stringp x)) (guard y (null y))) body2)))) ``` -------------------------------- ### Match Multiple Hash Table Entries with 'hash-table-entries' (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Shows the 'hash-table-entries' pattern for matching multiple key-value pairs from a hash table. This example extracts and processes values for keys ':a' and ':b'. ```lisp ;; Multiple entries (let ((table (alexandria:plist-hash-table '(:a 1 :b "2")))) (match table ((hash-table-entries :a a :b (read b)) (+ a b)))) ;; => 3 ``` -------------------------------- ### Apply Accessor Function with 'access' Pattern (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Demonstrates the 'access' pattern, which applies an accessor function to the matched value before matching subpatterns. This example uses a custom power function. ```lisp ;; Access with custom function (defun ^2 (x) (* x x)) (match 2 ((access #'^2 4) :four)) ;; => :FOUR ``` -------------------------------- ### Match Multiple Constraints with 'and' Pattern (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Shows how the 'and' pattern can be used to enforce multiple constraints on a value simultaneously. This example matches a list based on its elements. ```lisp ;; Multiple constraints (match (list 1 2) ((and (list 1 _) (list _ 2)) :both-matched)) ;; => :BOTH-MATCHED ``` -------------------------------- ### Array Pattern Matching with Inline Patterns Source: https://github.com/guicho271828/trivia/wiki/Inline-Patterns.org Illustrates advanced array pattern matching using the '@@' inline pattern to define dimensions and content structure. This example shows how '@@' can be nested to specify complex arrangements of elements within an array, including assigning a central variable. ```lisp (match my-array ((array :dimensions '(101 101) :contents ((@@ 50 (@@ 101 _)) ((@@ 50 _) center (@@ 50 _)) (@@ 50 (@@ 101 _)))) center)) ;; or like this (match my-array ((array :dimensions '(101 101) :contents ((@@ 50 ((@@ 50 _) _ (@@ 50 _)) ((@@ 50 _) center (@@ 50 _)) (@@ 50 ((@@ 50 _) _ (@@ 50 _)))) center)) ``` -------------------------------- ### List Destructuring with `list` and `list*` Patterns in Common Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Explains the `list` and `list*` patterns for matching lists. `list` requires an exact length match, while `list*` allows matching a minimum number of elements followed by the rest of the list. Examples show exact length matching, length mismatches, and matching improper lists. ```lisp ;; Exact length matching with list (match '(1 2 3) ((list a b c) (+ a b c))) ;; => 6 ;; Length mismatch returns nil (match '(1 2 3) ((list x y) :matched)) ;; => NIL ;; list* matches with rest (match '(1 2 3) ((list* a b rest) (list a b rest))) ;; => (1 2 (3)) ;; Matching improper lists (match '(1 2 . 3) ((list* _ _ x) x)) ;; => 3 ``` -------------------------------- ### Match Numbers with Equality/Inequality Constraints in Lisp Source: https://github.com/guicho271828/trivia/wiki/Numeric-Patterns.org This snippet demonstrates how to use trivia's (= number) and (/= number) patterns to match if a value is a number and satisfies equality or inequality constraints. The example shows matching a number less than 10. ```lisp (let ((x 5)) (trivia:match x ((< 10) :lower))) :LOWER ``` -------------------------------- ### Combine Type Check with Binding using 'and' Pattern (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Illustrates the 'and' pattern, which requires all subpatterns to match the same value. This example shows combining a type check with binding a variable. ```lisp ;; Combine type check with binding (match 42 ((and (type integer) x) x)) ;; => 42 ``` -------------------------------- ### Defining and Using Inline Patterns for Series Assignment Source: https://github.com/guicho271828/trivia/wiki/Inline-Patterns.org Shows how to define a custom inline pattern 'row' using '=defpattern-inline=' and then utilize it within a larger pattern match. This example demonstrates assigning a series of variables to array elements based on the 'row' pattern, simplifying complex assignments. ```lisp (defpattern-inline row (n symbol) (mapcar (lambda (m) (symbolicate symbol m)) (iota n))) (match my-array ((array :dimensions '(101 101) :contents ((@@ 50 ((@@ 50 _) _ (@@ 50 _)) ((row 101 a_)) (@@ 50 ((@@ 50 _) _ (@@ 50 _)))) (+ a_0 a_20 a_40 a_60 a_80 a_100))) ``` -------------------------------- ### Object Destructuring with `class` and `structure` Patterns in Common Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Demonstrates how to match CLOS objects and structures using the `class` and `structure` patterns. This allows access to object slots during pattern matching. Examples include matching structures by slot name and by slot value, and matching CLOS objects with specified slot values. ```lisp ;; Define a structure (defstruct point x y) ;; Structure matching with make-instance style (match (make-point :x 1 :y 2) ((point :x x :y y) (+ x y))) ;; => 3 ;; Structure matching with slot style (match (make-point :x 10 :y 20) ((point (x a) (y b)) (list a b))) ;; => (10 20) ;; Class matching (defclass person () ((name :initarg :name :reader name) (age :initarg :age))) (match (make-instance 'person :name "Alice" :age 30) ((person name age) (format nil "~a is ~d" name age))) ;; => "Alice is 30" ;; Partial matching with specific slot values (match (make-point :x 5 :y 10) ((point (x 5)) :x-is-five) (_ :other)) ;; => :X-IS-FIVE ``` -------------------------------- ### Level 0 Pattern Matching Example (Common Lisp) Source: https://github.com/guicho271828/trivia/wiki/Level-0-Patterns.org Demonstrates how to use the `match0` function to check if a given `tree` conforms to a specific nested list structure. It binds variables based on the matched elements and evaluates a resulting expression. This function is part of the Level 0 pattern matching system. ```common-lisp (match0 tree ((list* x (list :hi! y _) _ z) (vector x y z))) ``` -------------------------------- ### Multiple Return Value Matching with `multiple-value-match` in Common Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Showcases the `multiple-value-match` macro, which is used for pattern matching against multiple return values from a single form. The examples demonstrate matching all return values and performing partial matching when only some values are relevant. ```lisp ;; Matching against multiple values (multiple-value-match (values 1 2 3) ((x y z) (list x y z))) ;; => (1 2 3) ;; With partial matching (multiple-value-match (values 1 2) ((1 y) y)) ;; => 2 ``` -------------------------------- ### Multi-Argument `match*` Macro in Common Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Details the `match*` macro, designed for matching multiple values simultaneously against corresponding pattern lists. The examples illustrate matching multiple arguments and using guard patterns across these arguments for conditional matching. ```lisp ;; Match multiple arguments at once (match* ((list 2) (list 3) (list 5)) (((list x) (list y) (list z)) (+ x y z))) ;; => 10 ;; With guard patterns across arguments (match* ((list 2) (list 3) (list 5)) (((list x) (list y) (list (guard z (= z (+ x y))))) z)) ;; => 5 ``` -------------------------------- ### Switching Optimizers in Lisp Source: https://github.com/guicho271828/trivia/wiki/Using-Alternative-Optimizer.org Demonstrates how to switch between the :trivial and :balland2006 optimizers in Lisp using the `in-optimizer` command. This allows for different pattern matching behaviors based on the chosen optimizer. The code shows equivalent function definitions compiled under each optimizer. ```lisp (in-optimizer :trivial) (defun a (x) (match x ((list :a :b y) 'list-third) ((vector :a y :b) 'vector-second)))) (in-optimizer :balland2006) ;; change the optimizer and recompile the code! (defun a (x) (match x ((list :a :b y) 'list-third) ((vector :a y :b) 'vector-second)))) ``` -------------------------------- ### Lisp Match Macro Clause for Class Pattern Source: https://github.com/guicho271828/trivia/wiki/What-is-pattern-matching?-Benefits?.org Illustrates the 'match' macro syntax for a class pattern in Lisp. It shows how to specify a structure type and its slot patterns, including variable binding and constant matching. ```lisp (match x ((foo (bar b) (baz :a)) ;; <-- pattern <--+ ...body1...) ;; <-- body <--+-- clause) ``` -------------------------------- ### Negative Matching with 'not' Pattern (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Shows the 'not' pattern, which matches only if the subpattern does not match the input. This example demonstrates simple negative matching. ```lisp ;; Negative matching (match 1 ((not 2) :not-two)) ;; => :NOT-TWO ``` -------------------------------- ### Match Values Satisfying a Predicate with 'satisfies' Pattern (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Shows the 'satisfies' pattern, which matches values that satisfy a given predicate function. This example uses `evenp`. ```lisp ;; Predicate matching (match 4 ((satisfies evenp) :even)) ;; => :EVEN ``` -------------------------------- ### Split Strings and Match Parts in Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Demonstrates splitting strings by a delimiter and matching the resulting list elements. Also shows combining split with read for parsing numeric values. ```lisp ;; Split and match parts (match "1 2 3" ((split " " a b c) (list a b c))) ;; => ("1" "2" "3") ;; Combined with read for parsing (match "1 2 3" ((split " " (read a) (read b) (read c)) (+ a b c))) ;; => 6 ``` -------------------------------- ### Destructuring Let with Pattern Matching in Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Shows how to use the `let-match` macro for destructuring bindings with pattern matching, including multiple pattern bindings. ```lisp ;; Multiple pattern bindings (let-match ((a 1) ((list _ c d) (list 1 2 3)) ((cons e f) '(4 . 5))) (list a c d e f)) ;; => (1 2 3 4 5) ``` -------------------------------- ### Create Anonymous and Named Functions with Pattern Matching in Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Illustrates creating anonymous functions using `lambda-match` and named functions with pattern matching on arguments using `defun-match*`. ```lisp ;; Lambda with pattern matching (funcall (lambda-match ((list x y) (+ x y)) (x x)) '(1 2)) ;; => 3 ;; Define named function with matching (defun-match* point-distance (p1 p2) (((point (x x1) (y y1)) (point (x x2) (y y2))) (sqrt (+ (expt (- x2 x1) 2) (expt (- y2 y1) 2))))) (point-distance (make-point :x 0 :y 0) (make-point :x 3 :y 4)) ;; => 5.0 ``` -------------------------------- ### Run Gomoku Benchmark (Lisp) Source: https://github.com/guicho271828/trivia/blob/master/benchmark.org Implements the Gomoku benchmark, which simulates a game and counts Black and White moves. It iterates 100 times, processing a test set, and formats the final scores. This snippet is used across multiple test configurations. ```lisp (ITER OUTER (REPEAT 100) (ITER (FOR TEST IN *GOMOKU-TESTSET*) (CASE (FUNCALL FN TEST) (0 (IN OUTER (COUNTING T INTO BLACK))) (1 (IN OUTER (COUNTING T INTO WHITE))))) (FINALLY (FORMAT T "~& Black : White : Notany = ~a : ~a : ~a " BLACK WHITE (- (* 30 (LENGTH *GOMOKU-TESTSET*)) BLACK WHITE)) (RETURN-FROM OUTER (LIST BLACK WHITE)))) ``` -------------------------------- ### Lisp Destructuring with Match and Structs Source: https://github.com/guicho271828/trivia/wiki/Type-based-Destructuring-Patterns.org Demonstrates how to destructure a Lisp struct using the 'match' macro with different styles: make-instance, with-slots, and slot names. This allows binding struct slot values to variables. ```lisp (defstruct foo bar baz) (defvar *x* (make-foo :bar 0 :baz 1)) (match *x* ((foo :bar a :baz b) ;; make-instance style (values a b)) ((foo (bar a) (baz b)) ;; with-slots style (values a b)) ((foo bar baz) ;; slot name (values bar baz))) ``` -------------------------------- ### Match Either Form with 'or' Pattern (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Demonstrates the 'or' pattern, which succeeds if any of its subpatterns match. This example shows matching different list structures and binding variables consistently. ```lisp ;; Match either form (match '(4 . 3) ((or (list 1 a) (cons a 3)) a)) ;; => 4 ``` -------------------------------- ### Lisp Assoc and Property List Pattern Matching Source: https://github.com/guicho271828/trivia/wiki/Type-based-Destructuring-Patterns.org Explains the 'assoc' and 'property' patterns in Lisp's Trivia library for matching elements within association lists and property lists. It covers syntax, key-based lookup, default values, and the 'alist' and 'plist' convenience patterns. ```lisp ;; Example for assoc pattern (conceptual, not runnable without context) ;; (match my-alist ;; ((assoc 'key '(value)) ...)) ;; Example for property pattern (conceptual, not runnable without context) ;; (match my-plist ;; ((property :key 'value) ...)) ;; Example for alist pattern (conceptual, not runnable without context) ;; (match my-alist ;; ((alist (:key value)) ...)) ;; Example for plist pattern (conceptual, not runnable without context) ;; (match my-plist ;; ((plist (:key value)) ...)) ``` -------------------------------- ### Guard with Multiple Conditions (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Shows how to use guards with multiple conditions, including pattern matching within the guard and arbitrary Lisp expressions. ```lisp ;; Guard with multiple conditions (match (list 2 5) ((guard (list x y) (= 10 (* x y))) :product-is-10)) ;; => :PRODUCT-IS-10 ``` -------------------------------- ### Basic Pattern Matching with match, ematch, cmatch Source: https://github.com/guicho271828/trivia/wiki/Match-and-Variants.org These macros perform pattern matching on a single argument. `match` returns nil if no pattern matches, `ematch` signals an error, and `cmatch` signals a correctable error. They evaluate the body of the first matching clause. ```Common Lisp ;; Syntax for single argument matching *match* /argument/ &body /{clause}*/ ---> /result/ *ematch* /argument/ &body /{clause}*/ ---> /result/ *cmatch* /argument/ &body /{clause}*/ ---> /result/ ;; Syntax for multiple arguments matching *match** (&rest /arguments/) &body /{multiclause}*/ ---> /result/ *ematch** (&rest /arguments/) &body /{multiclause}*/ ---> /result/ *cmatch** (&rest /arguments/) &body /{multiclause}*/ ---> /result/ ``` -------------------------------- ### Modify Matched Value In-Place using 'place' Pattern (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Introduces the 'place' pattern, which allows for modifying matched values in place using `setf`. This example modifies an element within a list. ```lisp ;; Modify matched value in place (let ((x (list 0 1))) (match x ((list (place a) b) (setf a :modified))) x) ;; => (:MODIFIED 1) ``` -------------------------------- ### Cons Cell Destructuring with `cons` Pattern in Common Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Illustrates the `cons` pattern for matching cons cells and destructuring them into their `car` and `cdr` components. The examples cover basic destructuring of a list into its head and tail, and matching a dotted pair. ```lisp ;; Basic cons destructuring (match '(1 2 3) ((cons x y) (list x y))) ;; => (1 (2 3)) ;; Nested cons matching (match '(1 . 2) ((cons a b) (+ a b))) ;; => 3 ``` -------------------------------- ### Continuable `cmatch` Macro with Error Handling in Common Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Explains the `cmatch` macro, a correctable variant that signals a continuable `match-error`. This allows for error handling using restarts, as demonstrated in the example where a `match-error` is caught and continued, resulting in `NIL`. ```lisp ;; Continuable matching with handler (handler-bind ((match-error #'continue)) (cmatch 1 (2 :matched))) ;; => NIL (continued from error) ``` -------------------------------- ### Lisp Lambda Satisfies Pattern Matching Workaround Source: https://github.com/guicho271828/trivia/wiki/Type-based-Destructuring-Patterns.org Addresses an issue with matching lambda forms in Trivia's 'satisfies' pattern. It provides examples of the broken behavior and a workaround using 'guard1' for lambda predicates, along with a diff showing a potential fix in the inference rule. ```lisp ;; Matches properly only after adding symbol check in unary-function ;; inference rule (match 2 ((satisfies (lambda (x) (evenp x))) :short)) ; => :EVEN or TYPE-ERROR ;; Workaround: Matches properly (match 2 ((guard1 x ((lambda (x) (evenp x)) x)) :even)) ; => :EVEN ;; Works as described only after unary-function inference rule is ;; modified to ensure the function is designated by a symbol before ;; doing the type inference (match :long-keyword ((satisfies (lambda (x) (> 5 (length (string x))))) :short) ((satisfies (lambda (x) (<= 5 (length (string x))))) :long)) ``` ```diff -((list function '?) +((list (and (type symbol) function) '?) ``` -------------------------------- ### Dynamic Regex Patterns with 'ppcre' (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Shows how to use dynamic regular expression patterns with the 'ppcre' matcher. The regex itself can be a variable, allowing for flexible matching. ```lisp ;; Dynamic regex patterns (let ((url-pattern "^/user/(\w+)/$")) (match "/user/alice/" ((ppcre url-pattern user-id) user-id))) ;; => "alice" ``` -------------------------------- ### Replacing Optima with Trivia in Package Definition Source: https://github.com/guicho271828/trivia/blob/master/README.org This code snippet demonstrates how to switch from using the Optima pattern matching library to Trivia. It involves changing the :use clause in a defpackage form from ':optima' to ':trivia'. This is a common first step when migrating projects to use Trivia. ```lisp (defpackage :playwithit (:use :cl - :optima)) + :trivia)) (in-package :playwithit) (match '(something #(0 1 2)) ((list a (vector 0 _ b)) (values a b))) ``` -------------------------------- ### Defining a Custom Cons Pattern in Trivia Source: https://github.com/guicho271828/trivia/blob/master/README.org This example shows how to define a new pattern using Trivia's `defpattern` macro. It creates a `cons` pattern that checks if an input is a cons cell and then deconstructs it into its car and cdr components, assigning them to variables `a` and `b`. This highlights Trivia's extensibility. ```lisp (defpattern cons (a b) (with-gensyms (it) `(guard1 (,it :type cons) (consp ,it) (car ,it) ,a (cdr ,it) ,b))) ``` -------------------------------- ### Define Reusable Pattern Macros in Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Explains and demonstrates the `defpattern` macro for defining reusable pattern macros that expand to primitive patterns, shown with custom cons and string-type specifier patterns. ```lisp ;; Define a custom cons pattern (defpattern my-cons (car cdr) (with-gensyms (it) `(guard1 (,it :type cons) (consp ,it) (car ,it) ,car (cdr ,it) ,cdr))) ;; Define a string-type pattern (defpattern string-type-specifier (length) `(or (list 'string ,length) (and 'string (<> ,length '*)))) (match '(string 10) ((string-type-specifier len) len)) ;; => 10 (match 'string ((string-type-specifier len) len)) ;; => * ``` -------------------------------- ### Match Multi-dimensional Arrays with Metadata and Contents (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Demonstrates matching multi-dimensional arrays using the `simple-array` and `row-major-array` patterns. It shows how to specify dimensions, rank, and contents for matching. ```lisp ;; 2D array matching (match #2A((0 1) (2 3)) ((simple-array :dimensions '(2 2) :rank 2 :contents ((a b) (c d))) (list a b c d))) ;; => (0 1 2 3) ;; Array with row-major access (match #2A((0 1) (2 3)) ((row-major-array :contents (a b c d)) (+ a b c d))) ;; => 6 ``` -------------------------------- ### Lisp Pattern Matching with FAIL Macro Source: https://github.com/guicho271828/trivia/wiki/NEXT-FAIL-SKIP-macro.org This Lisp code snippet demonstrates pattern matching using the 'match' special form. It checks if a list starting with ':a' followed by a number 'x' is divisible by 3 or 5, returning 'fizz', 'buzz', or failing. The 'FAIL' macro is used to indicate a non-match. ```lisp #+BEGIN_SRC lisp (match '(:a 2) ((list :a x) (if (zerop (mod x 3)) 'fizz (fail)))) ((list :a x) (if (zerop (mod x 5)) 'buzz (fail))))) #+END_SRC ``` -------------------------------- ### Error-Signaling `ematch` Macro in Common Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Introduces the `ematch` macro, an error-signaling variant of `match`. It raises a `match-error` condition when no patterns match, which is particularly useful for ensuring exhaustive pattern matching. The example shows how it signals an error with non-matching patterns and behaves safely when patterns are exhaustive. ```lisp ;; Signals match-error if no pattern matches (ematch 1 (2 :two) (3 :three)) ;; => Signals MATCH-ERROR ;; Safe when patterns are exhaustive (ematch '(1 2) ((list a b) (+ a b))) ;; => 3 ``` -------------------------------- ### Match Single Association List Entry with 'assoc' (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Shows how to match a single key-value pair in an association list (alist) using the 'assoc' pattern. It extracts the value associated with a specific key. ```lisp ;; Single assoc match (match '((1 . 2) (3 . 4)) ((assoc 3 val) val)) ;; => 4 ``` -------------------------------- ### Vector Destructuring with `vector` and `vector*` Patterns in Common Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Covers the `vector` and `vector*` patterns for matching vectors. `vector` matches vectors of an exact length, while `vector*` matches vectors with a minimum length, capturing the remaining elements. Examples include exact matching, soft matching, and specialized string matching. ```lisp ;; Exact vector matching (match #(1 2 3) ((vector a b c) (+ a b c))) ;; => 6 ;; Soft matching with vector* (match #(1 2 3 4) ((vector* a b _) (+ a b))) ;; => 3 ;; Specialized vector types for performance (match "hello" ((simple-string h e l l o) (list h e))) ;; => (#\h #\e) ``` -------------------------------- ### Extended Constant Pattern Matching in Optima Source: https://github.com/guicho271828/trivia/wiki/Known-Differences Illustrates Optima's extended interpretation of constant patterns, allowing symbols within structural constants (arrays, structs) to be parsed as patterns. This enables more flexible matching against data structures. ```lisp (match #(0 1 2) (#(_ b 2) b)) ;; -> 1 (match #2A((0 1 2) (3 4 5)) (#2A((_ b 2) (_ _ f)) (+ b f))) ;; 1+5 -> 6 (match #S(person :name "bob") (#S(person :name name) name)) ;; -> "bob" ``` -------------------------------- ### Anonymous Function and Function Definition Pattern Matching Source: https://github.com/guicho271828/trivia/wiki/Match-and-Variants.org These macros provide convenient ways to define functions that immediately perform pattern matching on their arguments. They include variants for anonymous functions (`lambda-*`) and named functions (`defun-*`), supporting both single and multiple clauses, and differing in error handling. ```Common Lisp ;; Syntax for lambda variants *lambda-match* &body /{clauses}*/ ---> /result/ *lambda-ematch* &body /{clause}*/ ---> /result/ *lambda-cmatch* &body /{clause}*/ ---> /result/ *lambda-match** &body /{multiclause}*/ ---> /result/ *lambda-ematch** &body /{multiclause}*/ ---> /result/ *lambda-cmatch** &body /{multiclause}*/ ---> /result/ ;; Syntax for defun variants *defun-match* name (arg) &body /{clause}*/ ---> /result/ *defun-ematch* name (arg) &body /{clause}*/ ---> /result/ *defun-cmatch* name (arg) &body /{clause}*/ ---> /result/ *defun-match** name args &body /{multiclause}*/ ---> /result/ *defun-ematch** name args &body /{multiclause}*/ ---> /result/ *defun-cmatch** name args &body /{multiclause}*/ ---> /result/ ``` -------------------------------- ### Match Multiple Alist Entries with 'alist' Pattern (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Demonstrates matching multiple key-value pairs within an association list using the 'alist' pattern. This allows destructuring several entries simultaneously. ```lisp ;; Multiple alist entries (match '((1 . 2) (2 . 3) (3 . 4)) ((alist (3 . x) (1 . y)) (+ x y))) ;; => 6 ``` -------------------------------- ### AND Pattern Matching in Lisp Source: https://github.com/guicho271828/trivia/wiki/Logic-Based-Patterns.org Illustrates the AND pattern, which requires all subpatterns to match the element. This is useful for verifying multiple conditions on a single element. ```lisp (match x ((and (list 1 _) (list _ 2)) t)) ``` ```lisp (match x ((list 1 2) t)) ``` -------------------------------- ### Gomoku Winning Pattern Matching (Lisp) Source: https://github.com/guicho271828/trivia/wiki/Benchmarking-Results.org Matches randomly generated 5x5 Gomoku game fields against winning patterns to determine if Black or White is winning. It processes a large number of fields for each matcher. ```lisp ;; Matches a set of randomly generated 5x5 fields of Gomoku table game ;; against the /winning patterns/ of the game, in order to determine if a ;; Black player is winning, or a White player is winning. ;; 100000 fields are generated and fixed, then supplied to each matcher. (defun gomoku (fields) (let ((black-win 0) (white-win 0)) (dolist (field fields) (when (black-wins-p field) (incf black-win)) (when (white-wins-p field) (incf white-win))) (list :black black-win :white white-win))) ``` -------------------------------- ### Simple Array Pattern Syntax Source: https://github.com/guicho271828/trivia/wiki/Type-based-Destructuring-Patterns.org Defines the syntax for matching a simple array, its contents, and meta-level information like size and element type. This is a wrapper around the base ARRAY pattern and is used when ADJUSTABLE, HAS-FILL-POINTER, and DISPLACED-TO are all NIL. ```lisp (simple-array &key element-type dimensions rank total-size contents) ``` -------------------------------- ### String-match Benchmark Execution (Common Lisp) Source: https://github.com/guicho271828/trivia/blob/master/benchmark.org Measures the execution time for string matching operations, likely involving a set of predefined strings. This snippet demonstrates the summation and counting logic for the string-match benchmark. ```Common Lisp (LET ((SUM (ITER (REPEAT 10000) (SUMMING (ITER (FOR WORD IN *LONGSTR*) (COUNT (FUNCALL FN WORD))))))) (FORMAT T "~& Matched ~a times" SUM) SUM) ``` -------------------------------- ### Plist Matching with Default Value and Found Flag (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Demonstrates advanced 'property' pattern usage, including providing a default value and checking if a property was found. ```lisp ;; With default value and foundp (match '(:a 1) ((property :b val 99 found) (list val found))) ;; => (99 NIL) ``` -------------------------------- ### Trivia PPCRE Patterns: ppcre, split, split* Source: https://github.com/guicho271828/trivia/wiki/Contrib-packages.org The trivia.ppcre package provides three patterns: 'ppcre', 'split', and 'split*'. The 'ppcre' pattern is a wrapper around 'ppcre:scan-to-strings' for regular expression matching. 'split' and 'split*' are wrappers around 'ppcre:split', with 'split*' being a soft-match variant. These patterns are used with the 'match' function to find and extract substrings based on regular expressions. ```lisp (match "abcccdddcd" ((ppcre "ab([cd]+)" var) var)) ;; -> "cccdddcd" ``` ```lisp (match "a b" ((split " " var) :does-not-match) ((split " " var var2 var3) :does-not-match) ((split " " var var2) (list var var2))) ;; -> ("a" "b") ``` ```lisp (match "a b" ((split* " " var) var) ;; -> ("a") ``` -------------------------------- ### Match Multiple Plist Properties with 'plist' Pattern (Lisp) Source: https://context7.com/guicho271828/trivia/llms.txt Shows how to match multiple properties from a property list using the 'plist' pattern. This allows destructuring several key-value pairs at once. ```lisp ;; Multiple plist properties (match '(:a 1 :b 2 :c 3) ((plist :c c :a a) (+ a c))) ;; => 4 ``` -------------------------------- ### Basic List Matching with `match` Macro in Common Lisp Source: https://context7.com/guicho271828/trivia/llms.txt Demonstrates the fundamental usage of the `match` macro for destructuring lists, matching constants and wildcards, handling multiple clauses with fallthrough, and performing nested pattern matching. This macro evaluates an expression against a series of clauses and returns the body of the first matching clause. ```lisp ;; Basic list matching with destructuring (match '(1 2 3) ((list x y z) (+ x y z))) ;; => 6 ;; Matching with constants and wildcards (match '(:a 2 10) ((list :a b _) b)) ;; => 2 ;; Multiple clauses with fallthrough (match '(foo bar) ((list 'baz _) :first) ((list 'foo x) x) (_ :default)) ;; => BAR ;; Nested pattern matching (match '(:a (3 4) 5) ((list :a (list _ c) _) c)) ;; => 4 ```