[plt-scheme] HTDP Exercise 9.5.7

From: Jos Koot (jos.koot at telefonica.net)
Date: Mon Apr 13 12:57:59 EDT 2009

If you want one pass through the list of prices, you can do so with one single auxiliary function. First consider how many arguments 
that auxiliary function should have?

Later you will learn (at Intermediate student level, section 3) how to write function average as a oneliner, but as for now you dont 
have all tools yet (and with good reason, mho)

----- Original Message ----- 
From: "S Brown" <ontheheap at gmail.com>
To: <plt-scheme at list.cs.brown.edu>
Sent: Monday, April 13, 2009 6:12 PM
Subject: [plt-scheme] HTDP Exercise 9.5.7

> 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
> solution:
> <pre>
> (define (checked-average-price toy-list)
>  (cond
>    ((empty? toy-list) (error 'checked-average-price "expected a non-
> empty list"))
>    (else (average-price toy-list))))
> (define (average-price toy-list)
>  (cond
>    ((empty? toy-list) 0)
>    (else (/ (sum-list toy-list)
>             (num-items toy-list)))))
> (define (sum-list a-list)
>  (cond
>    ((empty? a-list) 0)
>    (else (+ (first a-list)
>             (sum-list (rest a-list))))))
> (define (num-items a-list)
>  (cond
>    ((empty? a-list) 0)
>    (else (+ 1 (num-items (rest a-list))))))
> </pre>
> 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.
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme

Posted on the users mailing list.