sicp每日一題[2.7]

再思即可發表於2024-09-13

2.7

Alyssa’s program is incomplete because she has not specified the implementation of the interval abstraction. Here is a definition of the interval constructor:
(define (make-interval a b) (cons a b))
Define selector supper-bound and lower-bound to complete the implementation.


這道題目難度不大,比起前面的選擇函式,就是多了一個取最小值為下界,最大值為上界的步驟,直接利用現成的 min, max 即可。

; x 表示某個區間
(define (lower-bound x) (min (car x) (cdr x)))

(define (upper-bound x) (max (car x) (cdr x)))

(define helper (make-interval 1.0 1.0))
(define r1 (make-interval 6.12 7.48))
(define r2 (make-interval 4.465 4.935))

; 計算並聯電路的電阻,注意這裡不能化簡成 r1*r2/(r1+r2) 的形式
(define (parallel-resistance r1 r2)
  (div-interval helper (add-interval (div-interval helper r1)
                                     (div-interval helper r2))))
                                     
(display (parallel-resistance r1 r2))

; 執行結果
[2.581558809636278, 2.97332259363673]

相關文章