sicp每日一题[2.80]
Exercise 2.80
Define a generic predicate =zero? that tests if its argument is zero, and install it in the generic arithmetic package. This operation should work for ordinary numbers, rational numbers, and complex numbers.
这道题更简单,直接与0相比较就行,以下代码在 2.79 的基础上修改
(define (=zero? x) (apply-generic '=zero? x))
; 一般数字
(put '=zero? '(scheme-number) (lambda (x) (= x 0)))
; 有理数
(put '=zero? '(rational) (lambda (x) (= (numer x) 0)))
; 复数,这里我有点奇怪,用 (= (magnitude z) 0) 实现居然检查不出来,我也没找到原因是啥
(put '=zero? '(complex) (lambda (z) (= (real-part z) (imag-part z) 0)))
(install-scheme-number-package)
(define n1 (make-scheme-number 0))
(define n2 (make-scheme-number 10))
(=zero? n1)
(=zero? n2)
(newline)
(install-rational-package)
(define r1 (make-rational 5 10))
(define r2 (make-rational 0 20))
(=zero? r1)
(=zero? r2)
(newline)
(install-rectangular-package)
(install-polar-package)
(install-complex-package)
(define z1 (make-complex-from-real-imag 3 4))
(define z2 (make-complex-from-real-imag 0 0))
(=zero? z1)
(=zero? z2)
; 执行结果
'done
#t
#f
'done
#f
#t
'done
'done
'done
#f
#t