# Comp 210 Lab 4: More Recursion

Index:
List examples,
Natural number examples

There are too many examples here to do all during lab.
Instead, do some from each group during lab, and the rest on your own.

**Important for all examples:**

- Follow the design recipe.
- For each group of examples, use the same template, because
the functions are on the same kind of data.
- Use the stepper to help understand the programs.

## List examples

### Non-empty lists of numbers

**To do:**

- Make a data definition for non-empty lists of numbers.
Hint: The base case should
*not* be empty, since that is
not a non-empty list of numbers! What is a description of the
shortest non-empty lists of numbers?
- Develop a program which takes a non-empty list of numbers and returns the
average (aka, arithmetic mean) of all the numbers.
- Develop a program which takes a list of numbers and returns the
average of all the numbers.
For this example, arbitrarily define the average of an empty list
to be false.

Note: There are actually
two reasonable solutions to this, although
we hinted towards the usually preferable one.
### Mixed data lists

**To do:**

- Make a data definition for a value which is a symbol or a number.
- Make a data definition for lists containing symbols and/or numbers.
Examples would include
empty
(cons 1 (cons 5 (cons 0 empty)))
(cons 1 (cons 'hi empty))
(cons 'hello (cons 'there empty))

- Develop a program which computes the product of all the numbers in
a such a list.
The structure of your program should correspond with your choice
of data definition.

Note: There are two reasonable ways
to do this, although we hinted at the usually preferable one.
### Functions resulting in lists

**To do:**

- Develop a program which consumes a list of numbers and
another number and returns a list of the sums of the original
list and the second argument. E.g.,
(add-numbers (cons 1 (cons 3 (cons 4 empty))) 2)
=
(cons 3 (cons 5 (cons 6 empty)))

- Develop a program which consumes a list of numbers and returns
a list of all of those numbers which are positive.

## Natural Numbers

Natural numbers are all the non-negative integers. It is often
convenient to consider them with the following recursive data definition.

;; a natural number (nat) is one of
;; - 0
;; - (add1 n)
;; where n is a natural number

While we can type `(add1 (add1 (add1 0)))`, we can also use
the "shorthand" `3`.
**To do:**

- Develop a program which computes the factorial of a natural number.
- Develop a program which consumes a natural number and a symbol
and returns a list of that many copies of the symbol. E.g.,
(copies 3 'hi) = (cons 'hi (cons 'hi (cons 'hi empty)))

- Develop a program which consumes a natural number
*n* and returns
a list of the natural numbers from *n*-1 to 0.