University of Virginia, Department of Computer Science
CS200: Computer Science, Spring 2004

Notes: Friday 30 January 2004

Recusive Definitions on Lists

  1. Be very optimistic. Since lists themselves are recursive structures, we should be able to come up with a recursive definition for almost anything we can think of doing with a list.
    1. Assume we can solve a smaller version of the problem.
    2. Break the problem into the original list and its cdr.
  2. Think of the simplest version of the problem, something you can solve already. For lists, this is usually the null list. (Sometimes, it might be the length 1 list.)
  3. Combine them to solve the problem. For lists, we will usually do combine the result of the recursive evaluation on the cdr with the result of doing something with the car of the list.
Many recursive list procedures can be defined with this template:
(define (listproc lst)
  (if (null? lst)
      [[[ insert base case here ]]]
      ([[[ f ]]] (car lst) (listproc (cdr lst)))))
For example:
(define (sumlist lst)
  (if (null? lst) 
      (+ (car lst) (sumlist (cdr lst)))))
(define (insertl lst f stopval)
  (if (null? lst)
      (f (car lst) 
	 (insertl (cdr lst) f stopval))))

(define (sumlist lst) (insertl lst + 0))

(define (productlist lst) (insertl lst * 1))

(define (length lst) 
  (insertl lst (lambda (head rest) (+ 1 rest)) 0))

In mathematics you don't understand things, you just get used to them.
John Von Neumann
Using these Materials