Tail Calls - Wed, Nov 6


The way in which names are looked up in Scheme and Python is called lexical scope (or static scope). You can see what names are in scope by inspecting the definition.

(define f (lambda (x) (+ x y)))
(define g (lambda (x y) (f (+ x x))))

What happens when you call (g 3 7)? The answer to this question depends on your scope:

FOR PROJECT 4: Instead of just having lambda procedures, you'll need to implement mu procedures (a special form to create dynamically scoped procedures).

Tail Recursion

Functional Programming

Advantages of functional programming:

No for/while statements! Can we make basic iteration efficient?

Recursion and Iteration in Python

def factorial(n, k):
    if n == 0:
        return k
        return factorial(n-1, k*n)

The code block above runs in linear time and in linear space.

def factorial(n, k):
    while n > 0:
        n, k = n-1, k*n
    return k

The code block above runs in linear time but in constant space.

Tail Calls

A procedure call that has not yet returned is active. Some procedure calls are tail calls. A Scheme interpreter should support an unbounded number of active tail calls using only a constant amount of space.

A tail call is a call expression in a tail context: