老潘已转到http://www.panxingzhi.net/。所有旧文章如有改动,此处将不再更新。谢谢。 I've moved to http://www.panxingzhi.net/. Updates on old posts are not applied here. Thanks.

SICP-2.80 solution

;; data-directed version

; generic zero? for all numbers
(define (zero? x) (apply-generic 'zero? x))

; inside scheme-number/rational/complex packages. note that we don't need to tag because the result is boolean
(put 'zero? '(scheme-number)
     (lambda (x) (= x 0)))
(put 'zero? '(rational)
     (lambda (x) (= (numer x) 0)))
; delegate to lower layer, or we should say, the sub packages
(put 'zero? '(complex) zero?)

; generic zero? for all complex
(define (zero?-complex x) (apply-generic 'zero? x))

; inside polar/rectangular packages. note that we don't need to tag because the result is boolean
(put 'zero? '(polar)
     (lambda (z) (= (magnitude z) 0)))
(put 'zero? '(rectangular)
     (lambda (z) (and (= (real-part z) 0) (= (imag-part z) 0))))






0 条评论:

添加评论