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

Notes: Monday 3 February 2003



What does cons do?

What do car and cdr do?

How could we define cons, car and cdr if Scheme did not have them as primitives?

A quintuple is a pair where ...

Why do we need the special list null?

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))

If you're in the penalty area and don't know what to do with the ball, put it in the net and we'll discuss the options later.
Bob Paisley

CS 200

CS 200: Computer Science
Department of Computer Science
University of Virginia
Using these Materials