[plt-scheme] HTDP Exercise 9.5.7

From: S Brown (ontheheap at gmail.com)
Date: Mon Apr 13 12:12:50 EDT 2009

I'm working my way through HTDP and I have a question regarding
Exercise 9.5.7. The exercise asks you to define the function average-
price, which takes as it's input a list of prices, and gives as output
the average of the prices in the list. I came up with  the following

(define (checked-average-price toy-list)
    ((empty? toy-list) (error 'checked-average-price "expected a non-
empty list"))
    (else (average-price toy-list))))

(define (average-price toy-list)
    ((empty? toy-list) 0)
    (else (/ (sum-list toy-list)
             (num-items toy-list)))))

(define (sum-list a-list)
    ((empty? a-list) 0)
    (else (+ (first a-list)
             (sum-list (rest a-list))))))

(define (num-items a-list)
    ((empty? a-list) 0)
    (else (+ 1 (num-items (rest a-list))))))

I came to this solution after not being able to figure out how to keep
track of the sum of the items and also the number of items at the same
time. So my concern/question is, is my solution acceptable, or should
I keep trying to figure out how to keep track of both values (sum and
number of items) without resulting to helper-functions such as sum-
list and num-items? Thanks.

Posted on the users mailing list.