088-pmatch-literals.scm (1361B)
1 ; pmatch — literal-shaped patterns: string, char, bool, sym, (). 2 3 ;; String pattern: byte-for-byte equality. 4 (if (= 1 5 (pmatch "hi" 6 ("ho" (sys-exit 90)) 7 ("hi" 1) 8 (else (sys-exit 91)))) 9 0 (sys-exit 1)) 10 11 ;; Character literals are integers; #\A == 65. 12 (if (= 65 13 (pmatch #\A 14 (#\B (sys-exit 92)) 15 (#\A 65) 16 (else (sys-exit 93)))) 17 0 (sys-exit 2)) 18 19 ;; #t / #f match by eq?. 20 (if (= 11 21 (pmatch #t 22 (#f (sys-exit 94)) 23 (#t 11))) 24 0 (sys-exit 3)) 25 26 ;; Bare symbol pattern matches that exact symbol; ,x in a sibling 27 ;; clause is the binder spelling. 28 (if (eq? 'matched 29 (pmatch 'foo 30 (bar 'no-bar) 31 (foo 'matched) 32 (,x 'fallback))) 33 0 (sys-exit 4)) 34 35 ;; Symbol-vs-binder: ,x binds anything; the literal symbol clause 36 ;; for `foo` only fires on exactly `foo`. 37 (if (eq? 'bound-baz 38 (pmatch 'baz 39 (foo 'literal-foo) 40 (,x (if (eq? x 'baz) 'bound-baz 'unexpected)))) 41 0 (sys-exit 5)) 42 43 ;; () pattern matches the empty list and nothing else. 44 (if (= 22 45 (pmatch '() 46 ((,h . ,t) (sys-exit 95)) 47 (() 22))) 48 0 (sys-exit 6)) 49 50 ;; () pattern doesn't match a non-empty list. 51 (if (= 33 52 (pmatch '(a) 53 (() (sys-exit 96)) 54 ((,_) 33))) 55 0 (sys-exit 7)) 56 57 (sys-exit 0)