[ prog / sol / mona ]

prog


Pattern Matching for MIT Scheme

2 2018-10-28 00:54 *

Instead I had to use Oleg Kiselyov's simple match macro :

(define-syntax match
  (syntax-rules ()
    ((__ exp clause ...)
      (let ((val-to-match exp))
 (match* val-to-match clause ...)))))

(define (match-failure val)
  (error "failed match" val))

(define-syntax match*
  (syntax-rules (else)
    ((__ val (else exp ...))
      (let () exp ...))
    ((__ val)
      (match-failure val))
    ((__ val (pattern () exp ...) . clauses)
      (let ((fail (lambda () (match* val . clauses))))
   ; note that match-pattern may do binding. Here,
   ; other clauses are outside of these binding
 (match-pattern val pattern (let () exp ...) (fail))))
    ((__ val (pattern guard exp ...) . clauses)
      (let ((fail (lambda () (match* val . clauses))))
 (match-pattern val pattern
   (if guard (let () exp ...) (fail))
   (fail))))
))

; (match-pattern val pattern kt kf)
(define-syntax match-pattern
  (syntax-rules (_ quote unquote)
    ((__ val _ kt kf) kt)
    ((__ val () kt kf)
      (if (null? val) kt kf))
    ((__ val (quote lit) kt kf)
      (if (equal? val (quote lit)) kt kf))
    ((__ val (unquote var) kt kf)
      (let ((var val)) kt))
    ((__ val (x . y) kt kf)
      (if (pair? val)
 (let ((valx (car val))
       (valy (cdr val)))
   (match-pattern valx x
     (match-pattern valy y kt kf)
     kf))
 kf))
    ((__ val lit kt kf)
      (if (equal? val (quote lit)) kt kf))))

Well, it worked. Still, I could rewrite the concerned parts one of these days. I haven't yet tested Adam Massma's port of the portable hygienic pattern matcher.

9


VIP:

do not edit these