Functional Problem Solving (CSC 151 2015F) : EBoards

CSC151.01 2015F, Class 31: Numeric Recursion


Overview

Preliminaries

Admin

Upcoming Work

Extra Credit Opportunities

Academic

Peer Support

Upcoming Peer Support

Good Things to Do, No EC

Questions

What are you doing with our questions on lab 30?

Questions have started to arrive. I am sending answers when I can.

I am gathering all of the questions and answers in a document that I will release in class on Wednesday. Make sure to get your questions in before then.

It helps to try the lab.

What should we do if we don't finish a lab or lab writeup in class?

Required: Finish the writeup.

Preferred (but not required): Finish the lab.

Preferred (but not required): With your partner.

Key ideas from pre-break lab

A few minutes with partner: Consider the following code.

;;; Parameters:
;;;   colors, a non-empty list of IRGB colors
(define irgb-brightest
  (lambda (colors)
    (cond
      [(null? (cdr colors))
       (car colors)]
      [(>= (irgb-brightness (car colors)) 
           (irgb-brightness (irgb-brightest (cdr colors))))
       (car colors)]
      [else
       (irgb-brightest (cdr colors))])))

What should this code do?

What's wrong?

How would you figure out that your code was this inefficient?

How to fix?

Technique one: Use a recursive kernel

(define irgb-brightest
  (lambda (colors)
    (irgb-brightest-kernel (cdr colors) (car colors))))

 (define irgb-brightest-kernel
   (lambda (colors brightest-so-far)
     (cond 
       [(null? colors)
        brightest-so-far]
       [(>= (irgb-brightness (car colors))
            (irgb-brightness brightest-so-far))
        (irgb-brightest-kernel (cdr colors) (car colors))]
       [else
        (irgb-brightest-kernel (cdr colors) brightest-so-far)])))

Technique two: When you have repeated code, use let to name the repeated code.

(define irgb-brightest
  (lambda (colors)
    (if (null? (cdr colors))
        (car colors)
        (let ([brightest-in-rest (irgb-brightest (cdr colors))])
          (if (>= (irgb-brightness (car colors)) 
                  (irgb-brightness brightest-in-rest))
              (car colors)
              brightest-in-rest)))))

Technique three: Try to avoid the second recursive call by using another helper procedure.

Lab

Writeup: Exercise 3