lec17 - (Const (+ v1 v2)))] [(Negate? e) (Const (- 0...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
(define (anything-to-num v) (cond [(number? v) 1] [(procedure? v) 2] [(cons? v) (+ (anything-to-num (car v)) (anything-to-num (cdr v)))] [(string? v) (string-length v)] [(symbol? v) 5] [(null? v) 6] [#t 7])) ;; suppose we wanted a "one-of type" using nothing but lists and symbols ;; and such, like ML's ;; datatype exp = Const of int | Add of exp * exp | Negate of exp ; (define (Const i) (list 'Const i)) (define (Add e1 e2) (list 'Add e1 e2)) (define (Negate e) (list 'Negate e)) ( ;; these work for "any exp" (just in our heads), but not other things (define (Const? x) (eq? (car x) 'Const)) (define (Add? x) (eq? (car x) 'Add)) (define (Negate? x) (eq? (car x) 'Negate)) ( (define Const-int cadr) (define Add-e1 cadr) (define Add-e2 caddr) (define Negate-e cadr) ( ;; take any expression return a Const (define (eval-exp e) (cond [(Const? e) e] [(Add? e) (let ([v1 (Const-int (eval-exp (Add-e1 e)))] [v2 (Const-int (eval-exp (Add-e2 e)))])
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: (Const (+ v1 v2)))] [(Negate? e) (Const (- 0 (Const-int (eval-exp (Negate-e e)))))] [#t (error "eval-exp expected an exp")])) (define (test1) (eval-exp (Negate (Add (Const 2) (Const 2))))) ;; much more convenient is define-struct ; (for any conceptual record or datatype) (define-struct const (int)) (define-struct add (e1 e2)) (define-struct negate (e)) ( (define (eval-exp2 e) (cond [(const? e) e] [(add? e) (let ([v1 (const-int (eval-exp2 (add-e1 e)))] [v2 (const-int (eval-exp2 (add-e2 e)))]) (make-const (+ v1 v2)))] [(negate? e) (make-const (- 0 (const-int (eval-exp2 (negate-e e)))))] [#t (error "eval-exp2 expected an exp")])) (define (test2) (eval-exp2 (make-negate (make-add (make-const 2) (make-const 2))))) ;; but it's much more than convenience, the result of make-add is _not_ ;; a list (or anything else in Pure Scheme) ;...
View Full Document

Page1 / 2

lec17 - (Const (+ v1 v2)))] [(Negate? e) (Const (- 0...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online