Laboratory Exercises For Computer Science 151

Flat Recursion

Flat Recursion

The beginning of Section 4.2 in our textbook states:

In our examples of recursion involving lists, we made the recursive step by applying the procedure to the cdr of the list. The car of the list was then treated as a unit, which is why the recursion was over the top-level items in the list. We refer to a recursion over the top-level items of a list as a flat recursion, and we say that the procedure so defined is flatly recursive or simply a flat procedure.

Goals: This laboratory procedure reviews flat recursion, clarifying this general approach to problem solving, considering a few more examples, and applying flat recursion to the solution of a few more problems.

Preparation: Reread section 4.2 of the textbook.

Problems For This Lab:

  1. Describe what the following procedure does:
    
    (define mystery
        (lambda (L)
            (cond ((null? L) 0)
                  ((number? (car L)) (+ 1 (mystery (cdr L))))
                  (else (mystery (cdr L)))
            )
        )
    )
    
    Hint: Look at several examples, such as (mystery '(7 a 1/2 b 3.14159 c -9)).
  2. Describe what the following procedure does:
    
    (define question-2
        (lambda (L)
            (cond ((null? L) #t)
                  ((not (number? (car L))) #f) 
                  (else (and (odd? (car L)) (question-2 (cdr L))))
            )
        )
    )
    
    Hint: Again, look at several examples, such as
    (question-2 '(7 a 1/2 b 3.14159 c -9))
    (question-2 '(1 3 5 7 9))
    (question-2 '(1 3 6 7 9))

  3. Write a procedure to-zero that changes all numbers in a list to 0 but leaves all other elements on the list unchanged. For example, (to-zero '(7 a 1/2 b 3.14159 c -9)) should return (0 a 0 b 0 c 0).

  4. Textbook Exercises: Solve exercises 4.1-4.4 from the textbook.

This document is available on the World Wide Web as

http://www.math.grin.edu/~walker/courses/151/lab-flat-recursion.html

created February 12, 1997
last revised February 13, 1997