;; C311 Programming Laguages ;; Fall 2008 ;; Dana Vrajitoru ;; Evaluation functions for the grammar that recognizes an arithmetic ;; expression. This version uses an extra parameter to communicate ;; information between the evaluations of the subtrees. (load-file "parse_expr.el") ;; Evaluation of a tree with the root 'E. This one can completely ;; ignore the previous value but we add it to all of them for ;; consistency. (defun eval1-E (Tree Prev) (if (or (< (length Tree) 3) (not (equal (car Tree) 'E))) nil (let ((Tres 0)) (setq Tres (eval1-T (cadr Tree) Prev)) (eval1-TT (elt Tree 2) Tres)))) (eval1-E '(E (T) (TT)) 0) 2 ; Defining this to be able to test the other functions. (defun eval1-T (Tree Prev) 2) ;; '(TT) when it expands to e. ;; '(TT (AO "+") (T ...) (TT ...)) (defun eval1-TT (Tree Prev) (if (or (not Tree) (not (equal (car Tree) 'TT))) nil (if (equal (length Tree) 1) Prev (let ((Tres (eval1-T (elt Tree 2) Prev)) (Next 0)) (cond ((equal (cadr (cadr Tree)) "+") (setq Next (+ Prev Tres)) (eval1-TT (elt Tree 3) Next)) ((equal (cadr (cadr Tree)) "-") (setq Next (- Prev Tres)) (eval1-TT (elt Tree 3) Next)) (t nil)))))) (eval1-TT '(TT) 1) 1 (eval1-TT '(TT (AO "+") (T) (TT)) 1) 3 (eval1-TT '(TT (AO "-") (T) (TT)) 1) -1 ; '(F 2) ; '(F a) ; '(F "(" (E ...) ")") (defun eval1-F (Tree Prev) (if (or (not Tree) (not (equal (car Tree) 'F))) nil (if (= (length Tree) 2) ; number or symbol (eval (cadr Tree)) (eval1-E (elt Tree 2) Prev)))) (eval1-F '(F 2) 0) (setq a 5) 5 (eval1-F '(F a) 0) 5 (eval1-F '(F "(" (E (T) (TT)) ")" ) 0) 2 ; Parses the list of tokens and build a parse tree, then calls the ; evaluation of the tree and returns the value. ((defun process (L) (let ((Tree (parse-input L))) (if (not Tree) nil (princ "The parse tree is:\n") (prin1 Tree) (princ "\nThis is evaluated to\n") (eval1-E Tree 0))))