CS 251 Fall 2019 Principles of Programming Languages
Ben Wood
λ
CS 251 Fall 2019
Principles of Programming Languages
Ben Wood
λ
https://cs.wellesley.edu/~cs251/f19/
Tail Recursion
1 Tail Recursion
Topics
Recursion is an elegant and natural match for many computations and data structures.
- Natural recursion with immutable data can be space-
inefficient compared to loop iteration with mutable data.
- Ta
Tail recursion eliminates the space inefficiency with a simple, general pattern.
- Recursion over immutable data expresses iteration more
clearly than loop iteration with mutable state.
- More higher-order patterns: fold
2 Tail Recursion
Naturally recursive factorial
3
(define (fact n) (if (= n 0) 1 (* n (fact (- n 1)))))
Tail Recursion
Sp Space: e: O( ) Ti Time: O( )
How efficient is this implementation?
CS 240-style machine model
Re Registers
Stack Pointer Program Counter
St Stack Co Code Hea Heap
Call frame
Tail Recursion 4
fixed size, general purpose Call frame Call frame
arguments, variables, return address per function call cons cells, data structures, …