-
Notifications
You must be signed in to change notification settings - Fork 1
/
pmatch.ss
67 lines (61 loc) · 2.57 KB
/
pmatch.ss
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
;; This is a new version of pmatch (August 8, 2012).
;; It has two important new features:
;; 1. It allows for a name to be given to the pmatch if an error ensues.
;; 2. A line from the specification has been removed. (see below). Without
;; that line removed, it was impossible for a pattern to be (quote ,x),
;; which might be worth having especially when we write an interpreter
;; for Scheme, which includes quote as a language form.
;;; Code written by Oleg Kiselyov
;; (http://pobox.com/~oleg/ftp/)
;;;
;;; Taken from leanTAP.scm
;;; http://kanren.cvs.sourceforge.net/kanren/kanren/mini/leanTAP.scm?view=log
; A simple linear pattern matcher
; It is efficient (generates code at macro-expansion time) and simple:
; it should work on any R5RS (and R6RS) Scheme system.
; (pmatch exp <clause> ...[<else-clause>])
; <clause> ::= (<pattern> <guard> exp ...)
; <else-clause> ::= (else exp ...)
; <guard> ::= boolean exp | ()
; <pattern> :: =
; ,var -- matches always and binds the var
; pattern must be linear! No check is done
; _ -- matches always
; 'exp -- comparison with exp (using equal?) REMOVED (August 8, 2012)
; exp -- comparison with exp (using equal?)
; (<pattern1> <pattern2> ...) -- matches the list of patterns
; (<pattern1> . <pattern2>) -- ditto
; () -- matches the empty list
(define-syntax pmatch
(syntax-rules (else guard)
((_ v (e ...) ...)
(pmatch-aux #f v (e ...) ...))
((_ v name (e ...) ...)
(pmatch-aux name v (e ...) ...))))
(define-syntax pmatch-aux
(syntax-rules (else guard)
[(_ name (rator rand ...) cs ...)
(let ([v (rator rand ...)])
(pmatch-aux name v cs ...))]
[(_ name v) (error 'match "match ~s failed\n~s\n" 'name v)]
[(_ name v (else e0 e ...)) (begin e0 e ...)]
[(_ name v (pat (guard g ...) e0 e ...) cs ...)
(let ([fk (lambda () (pmatch-aux name v cs ...))])
(ppat v pat (if (and g ...) (begin e0 e ...) (fk)) (fk)))]
[(_ name v (pat e0 e ...) cs ...)
(let ([fk (lambda () (pmatch-aux name v cs ...))])
(ppat v pat (begin e0 e ...) (fk)))]))
(define-syntax ppat
(syntax-rules (unquote)
[(_ v pt kt kf)
(and (identifier? #'pt) (free-identifier=? #'pt #'_))
kt]
[(_ v () kt kf) (if (null? v) kt kf)]
; [(_ v (quote lit) kt kf) (if (equal? v (quote lit)) kt kf)]
[(_ v (unquote var) kt kf) (let ([var v]) kt)]
[(_ v (x . y) kt kf)
(if (pair? v)
(let ([vh (car v)] [vt (cdr v)])
(ppat vh x (ppat vt y kt kf) kf))
kf)]
[(_ v lit kt kf) (if (equal? v 'lit) kt kf)]))