|
Comp210: Principles of Computing and Programming
|
Solution 1: The base case should describe all lists of length one, the shortest possible non-empty lists:
; A non-empty-list-of-numbers (nelon) is one of ; - a cons, which has a first, a number, and rest, empty ; (cons num empty) ; - a cons, which has a first, a number, and rest, a nelon ; (cons num nelon)
In this case, the template looks as follows:
(define (func-for-nelon a-nelon) (cond [(empty? (rest a-nelon)) ...(first a-nelon)...] [(cons? (rest a-nelon)) ...(first a-nelon)...(func-for-nelon (rest a-nelon))...] [else 'Bad_input]))
Solution 2: We could use the definition of (perhaps-empty) list-of-numbers, that we've already seen.
; A non-empty-list-of-numbers is ; a cons, which has a first, a number, and rest, a list-of-numbers ; (cons num lon)
Here, the template is different, since it must refer to the template for a regular (non-empty) list-of-numbers. In particular, you don't make a recursive call; you think to yourself "Ah, a-nelon contains a (perhaps-empty) list; I'd better call a function for such regular ol' lists":
(define (f a-nelon) ...(first a-nelon)...(func-for-lon (rest a-nelon))...)
Here, to compute the average, what function(s) of general (perhaps-empty) lists do you want to call, as your helper?
Which is better?
The disadvantage of the first solution is that it breaks encapsulation to ask
whether the rest
is empty or not. The disadvantage of the second
solution is that it requires writing both a non-empty-list and a normal-list
version of the function. Try computing the average using each of these
templates. This course will prefer the second solution (although the textbook
prefers the first).
Last Revised Tuesday, 24-Aug-2004 13:49:09 CDT
©2004 Stephen Wong and Dung Nguyen