Advertisement
Guest User

The memoirs of Dr. John Racket

a guest
Feb 27th, 2015
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 2.13 KB | None | 0 0
  1. #lang racket
  2. (require rackunit
  3.          plai)
  4.  
  5. (define-type WAE
  6.   [num (n number?)]
  7.   [plus (lhs WAE?)
  8.         (rhs WAE?)]
  9.   [minus (lhs WAE?)
  10.          (rhs WAE?)]
  11.   [id (sym symbol?)]
  12.   [with (var id?)
  13.         (val WAE?)
  14.         (body WAE?)
  15.         ])
  16.    
  17. (define (parse sexp)
  18.   (cond
  19.     [(number? sexp) (num sexp)]
  20.     [(symbol? sexp) (id sexp)]
  21.     [(equal? (first sexp) '+)
  22.      (plus (parse (second sexp))
  23.            (parse (third sexp)))]
  24.     [(equal? (first sexp) '-)
  25.      (minus (parse (second sexp))
  26.             (parse (third sexp)))]
  27.     [(equal? (first sexp) 'with)
  28.      (with (parse (first (second sexp)))
  29.            (parse (second (second sexp)))
  30.            (parse (third sexp)))]
  31.     [else (error 'parse "Unexpected expression: ~a" sexp)]
  32.     ))
  33.  
  34. (define (interp ast)
  35.   (type-case WAE ast
  36.     [num (n) n]
  37.     [id (sym)
  38.         (error 'interp "Unbound identifier: ~a" sym)]
  39.     [plus (lhs rhs)
  40.           (+ (interp lhs)
  41.              (interp rhs))]
  42.     [minus (lhs rhs)
  43.            (- (interp lhs)
  44.               (interp rhs))]
  45.     [with (var val body)
  46.           (interp (subst var val body))]
  47.     ))
  48.  
  49.  
  50. (define (subst var val body)
  51.   (type-case WAE body
  52.     [num (n) (num n)]
  53.     [id (sym)
  54.         (if (equal? var body)
  55.             val
  56.             body)]
  57.     [plus (lhs rhs)
  58.           (plus (subst var val lhs)
  59.              (subst var val rhs))]
  60.     [minus (lhs rhs) 'FIXME]
  61.     [else (error 'subst "Unbound identifier: ~a" body)]
  62.     ))
  63.  
  64. ;;Testing suite------------------------------------------------------------
  65. (define e1 '5)
  66. (check-equal? (parse e1) (num 5))
  67. (check-equal? (interp (parse e1)) 5)
  68.  
  69. (define e2 '(+ 3 5))
  70. (check-equal? (parse e2) (plus (num 3) (num 5)))
  71. (check-equal? (interp (parse e2)) 8)
  72.  
  73. (define e3 '(with (x 25) x))
  74. (check-equal? (parse e3) (with (id 'x) (num 25) (id 'x)))
  75. (check-equal? (interp (parse e3)) 25)
  76.  
  77. (define e4 '(with (x 10) (+ x 90)))
  78. (check-equal? (parse e4) (with (id 'x) (num 10) (plus (id 'x) (num 90))))
  79. (check-equal? (interp (parse e4)) 100)
  80.  
  81. ;;=========================================================================
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement