乐正

Actions speak louder than words.

Sicp-ex3-24

问题

在上面的表格实现里,对于关键码的检查用equal?比较是否相等(它被assoc调用)。这一检查方式并不一定总是合适的。举例来说,我们可能需要一个采用数值关键码的表格,对于这种表格,我们需要的不是找到对应的数值的准确匹配,而可以是有一个容许误差的数值。请设计一个表格构造函数make-table,它以一个same-key?过程为参数,利用这个过程检查关键码的“相等”与否。make-table过程应该返回一个过程dispatch,可以通过它去访问对应于局部表格的lookupinsert!过程。

解答

练习3.24 (ex3-24.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
(define (make-table same-key?)
  (let ((local-table (list '*table*)))
    (define (assoc key records)
      (cond ((null? records) #f)
            ((same-key? key (caar records)) (car records))
            (else (assoc key (cdr records)))))
    (define (lookup key-1 key-2)
      (let ((subtable (assoc key-1 (cdr local-table))))
        (if subtable
            (let ((record (assoc key-2 (cdr subtable))))
              (if record
                  (cdr record)
                  #f))
            #f)))
    (define (insert! key-1 key-2 value)
      (let ((subtable (assoc key-1 (cdr local-table))))
        (if subtable
            (let ((record (assoc key-2 (cdr subtable))))
              (if record
                  (set-cdr! record value)
                  (set-cdr! subtable
                            (cons (cons key-2 value)
                                  (cdr subtable)))))
            (set-cdr! local-table
                      (cons (list key-1
                                  (cons key-2 value))
                            (cdr local-table)))))
      'ok)
    (define (dispatch m)
      (cond ((eq? m 'lookup-proc) lookup)
            ((eq? m 'insert-proc!) insert!)
            (else (error "Unknown operation -- TABLE" m))))
    dispatch))

(define operation-table (make-table equal?))

(define get (operation-table 'lookup-proc))

(define put (operation-table 'insert-proc!))

测试

1
2
3
4
5
(put 'hello 'world 'zhongyu)
;Value: ok

(get 'hello 'world)
;Value: zhongyu

draft

« sicp-ex3-23 sicp-ex3-25 »

Comments