sicp每日一题[2.78]

Exercise2.78

The internal procedures in the scheme-number package are essentially nothing more than calls to the primitive procedures +, -, etc. It was not possible to use the primitives of the language directly because our type-tag system requires that each data object have a type attached to it. In fact, however, all Lisp implementations do have a type system, which they use internally. Primitive predicates such as symbol? and number? determine whether data objects have particular types. Modify the definitions of type-tag, contents, and attach-tag from Section 2.4.2 so that our generic system takes advantage of Scheme’s internal type system. That is to say, the system should work as before except that ordinary numbers should be represented simply as Scheme numbers rather than as pairs whose car is the symbol scheme-number.


这道题难度不大,就是说我们在设计程序的时候,先用内置的 number? 函数来判断,如果确实是数字,那就不用添加 scheme-number 标签,否则还跟之前一样。

(define (attach-tag type-tag contents)
  (if (number? contents)
      contents
      (cons type-tag contents)))

(define (type-tag datum)
  (cond ((number? datum) 'scheme-number)
        ((pair? datum) (car datum))
        (else (error "Bad tagged datum: TYPE-TAG" datum))))

(define (contents datum)
  (cond ((number? datum) datum)
        ((pair? datum) (cdr datum))
        (else (error "Bad tagged datum: CONTENTS" datum))))

上网看了别人的答案后,我发现 install-scheme-number-package 也能做一定简化,如下所示:

(define (install-scheme-number-package)
  (put 'add '(scheme-number scheme-number) +)
  (put 'sub '(scheme-number scheme-number) -)
  (put 'mul '(scheme-number scheme-number) *)
  (put 'div '(scheme-number scheme-number) /)
  (put 'make 'scheme-number (lambda (x) (attach-tag 'scheme-number x)))
  'done)

(define (make-scheme-number n)
  ((get 'make 'scheme-number) n))

(install-scheme-number-package)

(define m (make-scheme-number 5))
(define n (make-scheme-number 10))
(add m n)
(sub m n)
(mul m n)
(div m n)

; 执行结果
'done
15
-5
50
1/2
posted @ 2024-11-15 19:24  再思即可  阅读(1)  评论(0编辑  收藏  举报