# Outline of Class 23: Recursion Repeated

Held: Monday, March 2, 1998

• I got back last night at midnight, and haven't even had a chance to glance at your exams. It's likely that I'll collapse tonight, so I won't have much chance to grade tonight, either.
• I also haven't had a chance to read email. I will do that today.
• Today's brown-bag lunch has the intimidating title of Windows NT Privileged Architecture. I have no idea whether or not it will be interesting.
• Any questions on assignment 4?
• The Scheme code in today's outline is unlikely to be precisely correct, although the general strategy is.

## Tail Recursion, Repeated

• It has been suggested that "any recursive function can be rewritten as a recursive function".
• What do you think? Is this really the case? The answer is yes.
• Scheme helps us view one mechanism. We'll pass the "what to do with the returned result" in as a parameter to the recursive call and then do it when we hit the base case.
• In effect, we turn
```(define (recursive arg)
(if (base? arg)
(basefun arg)
(something arg (recursive (simplify arg)))
)
)
```
into
```(define (recursive arg)
(tailrecursive arg (lambda (x) x)))
(define (tailrecursive arg extra)
(if (base? arg)
(extra (basefun arg))
(tailrecursive (simplify arg)
(lambda (result)
(something (extra result)))
)
)
)
```
• The "extra" thing in the tail recursive version is similar to a concept called a continutation.
• Consider the case of factorial
```(define (fact n)
(if (= n 0) 1
(* n (fact (- n 1)))))
```
• We can rewrite that as
```(define (fact n)
(tailfact n (lambda (x) x)))
(define (tailfact n cont)
(if (= n 0)
(cont 1)
(tailfact (- n 1)
(lambda (result) (* result n)))))
```
• We can also use other strategies for making recursive functions tail recursive. For example, in factorial we can do the multiplication first, and pass along an accumulated "multiplications so far" (that is, n*(n-1)*(n-2)*...*(n-k)).
• For example
```(define (fact n)
(accfact (n 1)))
(define (accfact n acc)
(if (= n 0) acc
(accfact (- n 1) (* acc n))))
```
• The first strategy is, of course, more general.

## Fibonacci

These notes are not yet available.

On to Introduction to Sorting
Back to Recursion, Revisited
Outlines: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
Current position in syllabus

Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.