Design Pattern: Recursion on List

A good way to understand the basic Lisp functions is to understand how they are implemented. We can specialize our previous recursive design pattern by using null? or pair? to test for the base case (empty list). Using pair? is a bit safer because it gives more protection against malformed data.

(define (myfun lst)
         (if (pair? lst)
                 (combine (car lst) (myfun (cdr lst)))
                 baseanswer ))

We can easily implement length using this pattern:


(define (length1 lst)
  (if (pair? lst)
      (1+ (length1 (cdr lst)))
      0) )

To sum the numbers in a list:


(define (sum lst)
  (if (pair? lst)
      (+ (car lst) (sum (cdr lst)))
      0) )

Contents    Page-10    Prev    Next    Page+10    Index