10-17-2013 HW e

posted Oct 17, 2013, 5:29 AM by Samuel Konstantinovich   [ updated Oct 17, 2013, 7:48 AM ]
Reminder Test Tomorrow. You won't have to write a recursive function, but you might have to trace through functions that are recursive.

Do Now:

(define (foo L)
  (if (null? L)
      0
      (+ (car L) (foo (cdr L) ) )
   )
)

1. Evaluate (foo '(9 3 4) )
2. What is a better name for the foo function.




Goal:
In order to understand recursion, you must understand recursion.

A. Think of the smallest/simplest possible answer to your function. (Empty list, starting value of a sequence etc.)
B. Write your if or cond that states when the base case should be used.

Factorial base case is 0!, which is 1.
(define (fact n)
  (if (= n 0) 
     1
     ;else something
   )
)

C. Can you write your function in terms of itself?   n! = n*(n-1)!   is a way to define factorial using factorial. We can use that relationship as the else of our function:

(define (fact n)
  (if (= n 0) 
     1                                ;base case
     (* n (fact (- n 1) ) )    ;recursive call
   )
)

____________________________________________________

We can make functions that use conditionals as well, if there are more than 1 base case or recursive case:

Count the number of even integers in a list has 1 base case and two recursive options.
-What is the base case?
-How do you write count in terms of count?
- What are the recursive options?

Write out the three options in a cond:

(define (countEvens L)
  (cond 
     (   ?????  baseCase)
     (   ?????  ?????  )
     (   else  ?????  )
  )
)

Homework:
Complete your fib code, and see what is the largest number you can run (fib n) on such that it completes in 1 minute or less.


Comments