Skip to main content

CSC 151.01, Class 20: Other forms of list recursion

Overview

  • Preliminaries
    • Notes and news
    • Upcoming work
    • Extra credit
    • Questions
  • Problem 6 from Friday’s lab
  • DrRacket tips and tricks
  • Reading summary
  • Lab
  • Debrief (?)

News / Etc.

Upcoming Work

  • No writeup for class 19.
  • Writeup for class 20 due Wednesday at 10:30 p.m.
  • Reading for Wednesday’s class: Numeric recursion
  • Exam 2 due Tuesday at 10:30 p.m..
  • Exam 2 cover sheets due Wednesday at the start of class
  • Exam 2 epilogue due Wednesday at 10:30 p.m.

Extra credit (Academic/Artistic)

  • Aspen Trio on Wednesday at 7:30 p.m.

Extra credit (Peer)

  • Volleyball vs. U. Dubuque, Tuesday at 7:00 p.m. (last home match!)

Extra credit (Misc)

Other good things

Questions

Problem 6 from Friday’s lab

(define furthest-from-zero-alt
  (lambda (numbers)
    (display (list 'furthest-from-zero-alt numbers)) (newline)
    (if (null? (cdr numbers))
        (car numbers)
        (if (>= (abs (car numbers)) 
                (abs (furthest-from-zero-alt (cdr numbers))))
            (car numbers)
            (furthest-from-zero-alt (cdr numbers))))))

Observation: While there were 5 total calls in (furthest-from-zero '(5 4 3 2 1)), there were about 3 in `(furthest-from-zero ‘(1 2 3 4 5)).

Problem: In the latter case, each call to the procedure generates two identical recursive calls (one for the test, one for the result). And each of those recursive calls generates two. And so on and so forth.

Moral: Two identical recursive calls are expensive. Avoid repeated code.

A solution: Name the recursive result using let.

(define furthest-from-zero-alt
  (lambda (numbers)
    (display (list 'furthest-from-zero-alt numbers)) (newline)
    (if (null? (cdr numbers))
        (car numbers)
        (let ([result-from-magic-fairy
               (furthest-from-zero-alt (cdr numbers))])
          (if (>= (abs (car numbers)) 
                  (abs result-from-magic-fairy))
              (car numbers)
              result-from-magic-fairy)))))

DrRacket tips and tricks

Or: Watch Sam have difficulty with DrRacket.

Reading summary

Missed.

Lab

Whoops. (min 6.33 0) => 0.0

Writeup: 3de. No documentation necessary.

Debrief (and more)

Note: Finding common approaches and representing them somewhere is useful.

Note: To reduce, you need a procedure that returns the same type as the parameters. So, you can’t find the smallest using <, since that takes two numbers and returns #t/#f. You find the smallest using min or (lambda (a b) (if (<= a b) a b)).

Friday’s quiz! I will give you pictures of everyone in class