;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname my-eval) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) ; an Op (operator) is one of: '+, '-, '*, '/ ; an NExp (numeric expression) is one of ; - Number ; - (cons Op LOE) ; an LOE (list of epressions) is one of ; - empty ; - (cons NExp LOE) ; my-eval: NExp -> Number ; evaluate a numeric expression (check-expect (my-eval 5) 5) (check-expect (my-eval '(* 7 (+ 3 9))) 84) (check-expect (my-eval '(/ 8 (- 6 4))) 4) (check-expect (my-eval '(+ 8 7 2)) 17) (check-expect (my-eval '(* 12 6 2)) 144) (check-expect (my-eval '(- 8 7 2)) 3) ; right-associative (check-expect (my-eval '(/ 12 6 2)) 4) ; (define (my-eval exp) (cond [(number? exp) exp] [else (my-apply (first exp) (my-eval-all (rest exp)))])) ; my-eval-all: LOE -> LON ; evaluate every expression in the list (define (my-eval-all loe) (cond [(empty? loe) empty] [else (cons (my-eval (first loe)) (my-eval-all (rest loe)))])) ; my-apply: Op LON -> Number ; apply the operation to the given arguments (define (my-apply op args) (cond [(empty? args) (my-identity op)] [(symbol=? op '+) (+ (first args) (my-apply op (rest args)))] [(symbol=? op '-) (- (first args) (my-apply op (rest args)))] [(symbol=? op '*) (* (first args) (my-apply op (rest args)))] [(symbol=? op '/) (/ (first args) (my-apply op (rest args)))])) ; my-identity: Op -> Number ; return the value of the algebraic identity for the given operation (define (my-identity op) (cond [(or (symbol=? op '+) (symbol=? op '-)) 0] [(or (symbol=? op '*) (symbol=? op '/)) 1]))