To be noted: the last two exercises, 2.15 and 2.16 were left unfinished, and will be left for another time.
31 lines
1,011 B
Scheme
31 lines
1,011 B
Scheme
#lang sicp
|
|
#|
|
|
(define (add-interval x y)
|
|
(make-interval (+ (lower-bound x) (lower-bound y))
|
|
(+ (upper-bound x) (upper-bound y))))
|
|
|
|
(define (sub-interval a b)
|
|
(make-interval (- (lower-bound a) (upper-bound b))
|
|
(- (upper-bound a) (lower-bound b))))
|
|
|
|
Notice that in add-interval, the lower-bound is low-x + low-y.
|
|
Meanwhile the higher-bound is high-x + high-y = low-x + width-x
|
|
+ low-y + width-y = low-sum + (width-x + width-y).
|
|
So width-sum = width-x + width-y.
|
|
|
|
Similar logic applies to sub-interval.
|
|
|
|
For mul-interval it's enough to see that
|
|
(mul-interval (make-interval 1 2) (make-interval 3 4)) =
|
|
(3 . 8) -> width = 5
|
|
doesn't have the same width as:
|
|
(mul-interval (make-interval 3 4) (make-interval 3 4)) =
|
|
(9 . 16) -> width = 7
|
|
despite the fact that in both cases, the intervals have widths:
|
|
1 and 1.
|
|
|#
|
|
|
|
; This code is only here to pass hexlet's test, which I'm not sure is
|
|
; necessary.
|
|
(define (width x) (/ (- (upper-bound x) (lower-bound x))
|
|
2))
|