next up previous contents index
Next: Example Two: Quicksort Up: Examples Previous: Examples

Example One: Flatten

 

               

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)) 		  tex2html_wrap_inline972  		 (1 2 3)

(flatten '((1 2) 3) tex2html_wrap_inline972 (1 2 3)

(flatten '((1) (2) (3)) tex2html_wrap_inline972 (1 2 3)

(flatten '()) tex2html_wrap_inline972 ()

(flatten '((()))) tex2html_wrap_inline972 ()

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:
  1. We define a function flatten that takes one argument, l1.
  2. We branch using a cond statement, dependent on qualities of l1.
  3. If l1 is empty, we return the empty list; (flatten '())  tex2html_wrap_inline972  '(). 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.
  4. 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.
  5. 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.
  6. 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