Código: waev3.rkt
Descarga aquí
#lang plai
;; TDA para representar los árboles de sintaxis abstracta de WAE.
(define-type WAE
[id (i symbol?)]
[num (n number?)]
[binop (f procedure?) (izq WAE?) (der WAE?)]
[with (name symbol?) (named-expr WAE?) (body WAE?)])
;; Función que toma expresiones en sintaxis concreta y regresa el árbol de sintaxis abstracta
;; correspondiente.
;; parse: s-expression -> WAE
(define (parse sexp)
(match sexp
[(? symbol?) (id sexp)]
[(? number?) (num sexp)]
[(list 'with (list id val) body) (with id (parse val) (parse body))]
[(list op l r) (binop (elige op) (parse l) (parse r))]))
;; Función que hace un mapeo entre las funciones del lenguaje WAE y las funciones de Racket. Esta
;; función permite visualizar la relación entre el lenguaje anfitrión y el objetivo.
;; elige: symbol -> procedure
(define (elige sexp)
(match sexp
['+ +]
['- -]
['* *]
['/ /]))
;; Función que implementa el algoritmo de sustitución textual. Dada una expresion 'expr', un
;; identificador 'sub-id' y un valor 'val' se realiza la sustitucion expr[sub-id:=val].
;; subst: WAE symbol WAE -> WAE
(define (subst expr sub-id val)
(match expr
[(id i) (if (symbol=? i sub-id) val expr)]
[(num n) expr]
[(binop f izq der) (binop f (subst izq sub-id val) (subst der sub-id val))]
[(with bound-id named-expr body)
(if (symbol=? bound-id sub-id)
(with
bound-id
(subst named-expr sub-id val)
body)
(with
bound-id
(subst named-expr sub-id val)
(subst body sub-id val)))]))
;; Función que realiza el análisis semántico. Dado un árbol de sintaxis abstracta (ASA), regresa
;; la evaluación de éste.
;; interp: WAE -> number
(define (interp expr)
(match expr
[(id i) (error 'interp "Identificador libre")]
[(num n) n]
[(binop f izq der) (f (interp izq) (interp der))]
[(with bound-id named-expr body) (interp (subst body bound-id named-expr))]))