Skip to content

Instantly share code, notes, and snippets.

@fbanados
Created March 23, 2012 14:56
Show Gist options
  • Save fbanados/2171447 to your computer and use it in GitHub Desktop.
Save fbanados/2171447 to your computer and use it in GitHub Desktop.
Auxiliar 2 CC4101 - Lenguaje AE
#lang plai
(print-only-errors #t)
(define-type AE
[num (n number?)]
[bool (n boolean?)]
[bool-and (lhs AE?) (rhs AE?)]
[bool-or (lhs AE?) (rhs AE?)]
[bool-not (s AE?)]
[add (lhs AE?)
(rhs AE?)]
[sub (lhs AE?)
(rhs AE?)]
[if0 (test AE?) (then AE?) (else AE?)])
;; parse: sexp -> AE
;; Translate an s-expression to an AE
(define (parse sexp)
(cond
((number? sexp) (num sexp))
((boolean? sexp) (bool sexp))
((list? sexp)
(case (first sexp)
((+) (add (parse (second sexp))
(parse (third sexp))))
((-) (sub (parse (second sexp))
(parse (third sexp))))
((if0) (if0 (parse (second sexp))
(parse (third sexp))
(parse (fourth sexp))))
((and) (bool-and (parse (second sexp))
(parse (third sexp))))
((or) (bool-or (parse (second sexp))
(parse (third sexp))))
((not) (bool-not (parse (second sexp))))
))))
;; Tests
(test (parse '1) (num 1))
(test (parse '{+ {- 1 2 } 2 }) (add (sub (num 1) (num 2) ) (num 2)))
(test (parse '{- 3 {+ 1 2 } }) (sub (num 3) (add (num 1) (num 2) )))
;; Calculator Interpreter
;; calc: AE -> number
;; consumes an AE and computes the corresponding number
(define (calc ae)
(type-case AE ae
[num (n) n]
[add (lhs rhs) (+ (calc lhs) (calc rhs))]
[sub (lhs rhs) (- (calc lhs) (calc rhs))]
[if0 (test then else)
(if (= 0 (calc test))
(calc then)
(calc else))]
[bool (b) b]
[bool-and (left right) (and (calc left) (calc right))]
[bool-or (left right) (or (calc left) (calc right))]
[bool-not (exp) (not (calc exp))]))
;; Test cases
(test (calc (parse '3)) 3)
(test (calc (parse '{+ 3 4})) 7)
(test (calc (parse '{+ {- 3 4} 7})) 6)
(test (calc (parse '{if0 0 1 2})) 1)
(test (calc (parse '{if0 1 1 2})) 2)
(test (calc (parse '(and #t #f))) #f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment