aboutsummaryrefslogtreecommitdiffstats
path: root/csc/match.csc
blob: 5b85f0984e666126738a99e6c2255560d31a064a (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
(define-library (csc match)
  (export match)
  (import (scheme base))
  (begin


    (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* ...)
         (let ((y x))
           (if (= 1 (length y))
             (match-pattern (car y) pattern result result* ...)
             (raise (make-no-match)))))
        ((match-pattern x (pattern . rest) result result* ...)
         (let ((y x))
           (if (pair? y)
             (match-pattern (car y) pattern
               (match-pattern (cdr y) rest result result* ...))
             (raise (make-no-match)))))
        ((match-pattern x identifier result result* ...)
         (let ((identifier x))
           result result* ...))))


    (define-syntax match
      (syntax-rules ()
        ((match x (arm ...))
         (guard (e ((no-match? e) (if #f #f)))
           (match-pattern x arm ...)))
        ((match x (arm ...) clause clause* ...)
         (let ((y x))
           (guard (e ((no-match? e)
                      (match y clause clause* ...)))
             (match-pattern y arm ...))))))))