乐正

Actions speak louder than words.

Sicp-ex2-1

问题

请定义出make-rat的一个更好的版本,使之可以正确处理正数和负数。当有理数为正时, make-rat应当将其规范化,是它的分子和分母都是正的。如果有理数为负,那么就应只让 分子为负。

解答

练习2.1 (ex2-1.scm) download
1
2
3
4
5
6
7
8
9
(define (make-rat n d)
  (define (rat-operator)
    (if (or (and (< n 0) (> d 0))
            (and (> n 0) (< d 0)))
        -
        +))
  (let ((g (gcd n d)))
        (cons ((rat-operator) (abs (/ n g)))
              (abs (/ d g)))))

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
(define one-half (make-rat 1 2))

(print-rat one-half)
1/2
;Unspecified return value

(define minus-one-half (make-rat 1 -2))
;Value: minus-one-half

(print-rat minus-one-half)

-1/2
;Unspecified return value

(define minus-one-third (make-rat 3 -9))
;Value: minus-one-third

(print-rat minus-one-third)

-1/3
;Unspecified return value

draft

« sicp-ex1-46 sicp-ex2-2 »

Comments