Functional Problem Solving (CSC 151 2016S) : EBoards

CSC151.02 2016S, Class 31: Pause for Breath


Overview

Preliminaries

Admin

Reminders

Upcoming Work:

Extra Credit

Academic / Artistic

Peer

Regular Peer NOT DURING BREAK

Misc

Far in the Future

Questions

Why Use Helper Recursion?

A lot of the ways we've phrased recursion, the work happens in the future.

(define sum (lambda (lst) (if (null? lst) 0 (+ (car lst) (sum (cdr lst))))))

(sum '(3 1 4)) => (+ (car '(3 1 4)) (sum (cdr '(3 1 4)))) => (+ 3 (sum (cdr '(3 1 4)))) etc.

Delayed work, and this phrasing, can be confusing.

The computer also has to build a long list of work to do in the future.

So we look for alternatives. Something more close to what we do.

Sometimes, it's easier to think about recursion if you think about using a helper.

(define lav (lambda (lst) (display (list 'lav lst)) (newline) (cond [(null? (cdr lst)) (car lst)] [(>= (abs (car lst)) (abs (lav (cdr lst)))) (car lst)] [else (lav (cdr lst))])))

How do we fix this?

(define lav2 (lambda (lst) (display (list 'lav lst)) (newline) (cond [(null? (cdr lst)) (car lst)] [else (let ([lav-cdr (lav2 (cdr lst))]) (if (>= (abs (car lst)) (abs lav-cdr)) (car lst) lav-cdr))])))

Lab