2.1
练习 2.1 请定义出 make-rat 的一个更好的版本,使之可以正确处理正数和负数。当有理数为正时,make-rat 应当将其规范化,使它的分子和分母都是正的。如果有理数为负,那么就应只让分子为负。
优化前:
(define (make-rat n d) (cons n d))
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (print-rat x)
(newline)
(display (numer x))
(display "/")
(display (denom x)))
(print-rat (make-rat 1 2))
(print-rat (make-rat -1 -2))
(print-rat (make-rat 1 -2))
优化后:
(define (make-rat n d)
(if (> (* n d) 0)
(cons (abs n) (abs d))
(cons (- 0 (abs n)) (abs d))
)
)
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (print-rat x)
(newline)
(display (numer x))
(display "/")
(display (denom x)))
(print-rat (make-rat 1 2))
(print-rat (make-rat -1 -2))
(print-rat (make-rat 1 -2))