blob: 86efab7681545bab43934a08e05a4bb03faebf64 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
(define-library (csc match)
(export match)
(import (scheme base))
(begin
(define-syntax matches?
(syntax-rules (_ !)
((matches? x _) #t)
((matches? x '())
(null? x))
((matches? x (! constant))
(equal? x constant))
((matches? x (pattern))
(and (= 1 (length x))
(matches? (car x) pattern)))
((matches? x (pattern1 . pattern2))
(and (pair? x)
(matches? (car x) pattern1)
(matches? (cdr x) pattern2)))
((matches? x identifier) #t)))
(define-syntax bind-pattern
(syntax-rules (_ !)
((bind-pattern x _ result result* ...)
(begin result result* ...))
((bind-pattern x '() result result* ...)
(begin result result* ...))
((bind-pattern x (! constant) result result* ...)
(begin result result* ...))
((bind-pattern x (pattern) result result* ...)
(bind-pattern (car x) pattern result result* ...))
((bind-pattern x (pattern1 . pattern2) result result* ...)
(bind-pattern (car x) pattern1
(bind-pattern (cdr x) pattern2 result result* ...)))
((bind-pattern x identifier result result* ...)
(let ((identifier x))
result result* ...))))
(define-record-type <no-match>
(make-no-match)
no-match?)
(define-syntax match-pattern
(syntax-rules (_ ! when)
((match-pattern x pattern (when condition) result result* ...)
(match-pattern x pattern
(if condition
(begin result result* ...)
(raise (make-no-match)))))
((match-pattern x _ result result* ...)
(begin result result* ...))
((match-pattern x '() result result* ...)
(if (null? x)
(begin result result* ...)
(raise (make-no-match))))
((match-pattern x (! constant) result result* ...)
(if (equal? x constant)
(begin result result* ...)
(raise (make-no-match))))
((match-pattern x (pattern) result result* ...)
(if (= 1 (length x))
(match-pattern (car x) pattern result result* ...)
(raise (make-no-match))))
((match-pattern x (pattern . rest) result result* ...)
(if (pair? x)
(match-pattern (car x) pattern
(match-pattern (cdr x) rest result result* ...))
(raise (make-no-match))))
((match-pattern x identifier result result* ...)
(let ((identifier x))
result result* ...))))
(define-syntax match
(syntax-rules (when)
((match x (pattern result result* ...))
(guard (e ((no-match? e) (if #f #f)))
(match-pattern x pattern result result* ...)))
((match x (pattern result result* ...) clause clause* ...)
(guard (e ((no-match? e)
(match x clause clause* ...)))
(match-pattern x pattern result result* ...)))))))
|