# Non-empty Lists of Numbers

## 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)) … ]))

## 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 and the textbook will prefer the first solution.