乐正

Actions speak louder than words.

Sicp-ex4-3

问题

请重写eval使之能以一种数据导向的方式完成分派。请将这样做出的程序与练习2.73的数据导向程序做一个比较。(你可以用一个符合表达式的car来作为表达式的类型,采用像这一节中所实现的语法形式。)

解答

练习4.3 (ex4-3.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
(define (eval exp env)
  (let ((type (exp-type exp)))
    (apply-generic type (exp-content exp) env)))

(define (exp-type exp) (car exp))
(define (exp-content) (cdr exp))

(define operation-table (make-eq-hash-table))
(define (put key datum) (hash-table/put! operation-table key datum))
(define (get key) (hash-table/get operation-table key #f))

(define (apply-generic op . args)
  (let ((proc (get op)))
    (if proc
        (apply proc args)
        (error "Unknown expression type -- EVAL" exp))))

(define (eval-and exp env)
  (define (internal remains)
    (cond ((null? remains) #t)
          ((not (eval (car remains) env)) #f)
          (else (internel (cdr remains)))))
  (internal (cdr exp)))

(define (eval-or exp env)
  (define (internal remains)
    (cond ((null? remains) #f)
          ((eval (car remains) env) #t)
          (else (internal (cdr remains)))))
  (internal (cdr exp)))

(put 'and eval-and)
(put 'or eval-or)
(put 'self-evaluating (lambda (exp env) (exp)))
(put 'variable lookup-variable-value)
(put 'quoted (lambda (exp env) (text-of-quotation exp)))
(put 'assignment evel-assignment)
(put 'definition eval-definition)
(put 'if eval-if)
(put 'lambda (lambda (exp env)
                (make-procedure (lambda-parameters exp)
                                (lambda-body exp)
                                env)))
(put 'begin (lambda (exp env)
              (eval-sequence (begin-actions exp) env)))
(put 'cond cond->if)
(put 'application (lambda (exp env)
                    (apply (eval (operator exp) env)
                           (list-of-values (operands exp) env))))

draft

« sicp-ex4-2 sicp-ex4-4 »

Comments