Problem 7. (Extra credit) Your crazy instructors have taken on a consulting software development job. They agreed to help some financial company translate their data into a reasonable format. The good news is that they and the managers agreed on a data format:
(define-struct single (it rst))
(define-struct intval (low high rst))
+---------------------------------------+
|+----------------------------------+ |
|| | |
vv | |
;; A SON is one of: | |
;; -- 'done | |
;; -- (make-single Number SON) ----------+ |
;; -- (make-intval Number Number SON) --------+
The bad news is that they have never seen such a data definition before and simply don't know how to design a function that adds up all numbers in a SON. Do it for them!
;;; Grader: Matthias
;;; sum : SON -> Numbers
;;; Add up all the numbers in the given SON.
(define (sum ason)
;; [3 pts, 1 per cond line/CONDITION]
(cond [(symbol? ason) 0]
;; [1pt: single-it, nat rec]
[(single? ason) (+ (single-it ason) (sum (single-rst ason)))]
;; [1pt: intval-xxx, nat rec]
[else (+ (sum-interval (intval-low ason) (intval-high ason))
(sum (intval-rst ason)))]))
;; MF: OK TO JUST ADD UP THE TWO NUMBERS AND THE
;; RESULT OF THE NAT. REC.
[else (+ (intval-low ason)
(intval-high ason)
(sum (intval-rst ason)))]
;;; OS: IF THEY ARE SOPHISTICATED, GREAT!
;;; sum-interval : Number Number -> Number
;;; Return the sum of the integers in the range [lo,hi].
;;; E.g. (sum-interval 3 8) = 3 + 4 + 5 + 6 + 7 + 8
(define (sum-interval lo hi)
(/ (* (+ 1 (- hi lo))
(+ lo hi))))
;; TESTS: if they don't do that, they'll fail!
(equal? 0 (sum 'done))
(equal? 1 (sum (make-single 1 'done)))
(equal? 1 (sum (make-intval 1 1 'done)))
(equal? 11 (sum (make-intval 1 4 (make-single 1 'done))))