Next: Example Two: Quicksort
Up: Examples
Previous: Examples
The flatten function, given a list, returns a list of the
atoms in that list. In other words, it `flattens' the recursive list structure
of its argument. For instance,
(flatten '(1 2 3)) (1 2 3)
(flatten '((1 2) 3) (1 2 3)
(flatten '((1) (2) (3)) (1 2 3)
(flatten '()) ()
(flatten '((()))) ()
The flatten function may be defined as follows:
(define (flatten l1)
(cond
((null? l1) '())
((null? (car l1)) (flatten (cdr l1)))
((atom? (car l1)) (cons (car l1) (flatten (cdr l1))))
(else (append (flatten (car l1)) (flatten (cdr l1))))))
This function works in the following way:
- We define a function flatten that takes one argument, l1.
- We branch using a cond statement, dependent on qualities of
l1.
- If l1 is empty, we return the empty list;
(flatten '()) '(). In functions that operate on lists, checking the
argument for null? is typically the base case of the recursion, and the
first branch of the cond.
- If the first element in l1 is the
empty list, i.e., l1 looks like (() ...), we throw away that
element and return the flatten of the tail of l1.
- If the first
element is an atom, it cannot be the empty list, since that case was captured by
the previous branch. Thus, it is a normal atom, and we return that atom
cons'ed onto the flatten of the tail of l1.
- Lastly, if none
of the previous cases were true, the first element of l1 is itself a
non-empty list, and we return the flatten of that list appended to the
flatten of the tail of l1.
Steven J. Zeil
Tue Mar 4 14:36:27 EST 1997