University of California, Berkeley
EECS Department - Computer Science Division

CS3 Lecture 6

(define (recursion)
(recursion))

"...in order to understand recursion, one must first understand recursion"


Overview of today's lecture


Answers to questions that have come up

Review


Somebody overwrote count, what do we do?

: (define (count sw) -1)
length

: (count '(a b c))
-1
;; Given a sentence, return the number of words
;;
;; e.g.,
;; (my-count '(a b c)) ==> 3
;;
(define (my-count s)
==> (cond ((empty? s) 0)
==>       ((empty? (bf s)) 1)
==>       ((empty? (bf (bf s))) 2)
==>       ((empty? (bf (bf (bf s)))) 3)
==>        ... etc ... ))

Recursion

Recursion: (definition) noun. See recursion. (courtesy UMEC's Jargon file)

Recursion: Formal Definition (courtesy [NIST:dads])

An algorithmic technique where a function, in order to accomplish a task, calls itself with some part of the task.

Our first example: somebody overwrote count!

: (define (count sw) -1)
count

: (count '(a b c))
-1
(define (my-count s)
   (if (empty? s)
      0
      (+ 1 
         (my-count (butfirst s)))))
: (my-count '())
==> 0

: (my-count '(1 2 3))
==> 3

Another example: nothing-but-a-words?

;; Given a sentence of numbers, return the sum of all the numbers
;;
;; (nothing-but-a-words? '(adam ant and alan alda)) ==> #t
;; (nothing-but-a-words? '(an apple a day))         ==> #f
;;
(define (a-word? w) (equal? (first w) 'a))

(define (all? pred? s)
  (= (count s)
     (count (keep pred? s))))

(define (nothing-but-a-words? s)
   (all? a-word s))
(define (nothing-but-a-words? s)
   (cond ((= (count s) 0) #t)
         ((= (count s) 1) (a-word (first s)))
         ((= (count s) 2) (and (a-word (first s))
                               (a-word (first (bf s)))))
         ((= (count s) 3) (and (a-word (first s))
                               (a-word (first (bf s)))
                               (a-word (first (bf (bf s))))))
         ...etc
(define (nothing-but-a-words? s)
   (if (empty? s)
        #t
        (and (a-word? (first s)) 
              (nothing-but-a-words? (butfirst s))))


Summary

Next Time

Puzzle : The Checkerboard problem

             
             
               
               
             
               
               
             

Game : Domineering

References


WWW Maven: Dan Garcia (ddgarcia@cs.berkeley.edu) Send me feedback

Dan Garcia Berkeley Computer Science