Lecture 20 Scheme II, Tail Recursion
- Questions
- Dynamic Scope
- Lexical scope - The way in which names are looked up in Scheme and Python
- Parents of a frame is the environment in which a procedure was defined
- Dynamic Scope
- The parent of a frame is the environment in which a procedure was called
- Tail Recursion
- Functional Programming
- All functions are pure functions
- No re-assignment and no mutable data types
- Name-value bindings are permanent
- Advantages
- Value of an expression is independent of the order in which sub-expressions are evaluated
- Sub-expressions can safely be evaluated in parallel or only on demand (lazily)
- Referential transparency: value of an expression doesn’t change when we substitute one of its subexpression with the value of that subexpression
- Recursion and Iteration in Python
- Python recursive calls always create new active frames
- Tail recursion
- Making recursive functions more space efficient (constant space)
- Recursive functions in scheme should be tail recursive
- Factorial function
- Saving my value in the argument
- (factorial 6 1)
- (factorial 5 6)
- (factorial 4 30)
- …
- (factorial 1 720)
- 720
- Tail Calls
- A procedure call that has not yet returned is active
- 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:
- last body sub-expression in a lambda expression (or procedure definition)
- Sub expression 2 and 3 in a tail context if expression
- All non-predicate sub-expressions in a tail context cond
- Last sub expression in a tail context and, or, begin, or let
- Example: Length of a list
- Call expression is not a tail call if more computation is still required in the calling procedure
- Eval with Tail Call Optimization
- Tail Recursion Examples
- Every parent function needs to be tail recursive
- If we need to do more computation after we do the recursive function then it isn’t tail recursive
- Map and Reduce
- Take in an iterable
- Applies on every element in iterable
- Implementing Tail Call Optimization
- Thunk - An expression wrapped in an argument-less function
- Trampolining
- A loop that iteratively invokes thunk-returning functions
- You’ll eventually get back an answer when you keep calling a function
- A trampoline will just keep calling until you get an answer
- Scheme Practice
- Extra Tail Recursion Examples
1.