10-15-2013

posted Oct 15, 2013, 5:39 AM by Samuel Konstantinovich   [ updated Oct 15, 2013, 8:12 AM ]
Goal: Intro to recursion.

1. Remember we know functions that we can use on lists:  car, cdr, length, and null?
null? is true when the list is empty, false otherwise:
   (null? '(1 2 3) ) -> #f
   (null? '() ) -> #t
2. Discuss with your neighbors: How could we find the length of a list without using the length function?

The idea that we can count how many times we can take the cdr of the list was accepted to be something that would be a good plan, even if we don't know how to set it up.

(define (myLength L) 
   (if (null? L)
        0
        (+ 1 ?????(cdr L)  ) ) )

When the list is empty, we get 0.
When the list is not empty, we add 1 to something to do with the cdr.
What function should we use here at the ??????  ?

We really want to know how many elements are in the rest of the list... so using length would be great. 
More specifically, using MYLENGTH would be great... so we try to do that:

(define myLength (lambda (L) 
(if (null? L)
0
(+ 1 (myLength (cdr L) ) ) ) ) )


Think of 
(myLength '(2 3 9) )   It triggers the non 0 expression:

(+ 1 (myLength ( 3 9) ) )  
That myLength also triggers:

(+ 1 (+ 1 (myLength ( 9 ) ) )  
and again:

(+ 1 (+ 1 (+1 (myLength () ) ) )  
but that triggers the 0:

(+ 1 (+ 1 (+ 1 0) ) )  Which is 3.



Classwork/Homework:
1. Google recursion.
2. Write a factorial function.
Factorial is also recursive:
5! -> 5*4!
N! -> N*(N-1)!

in scheme   (fact n) ->  (* n (fact (- n 1) )
But you have to stop at 0, (fact 0) -> 1


Comments