61A Lecture 5
Friday, January 30
Announcements
- Quiz 1 scores will be posted eventually, but you already know what you'll get
- Guerrilla Section 1 on higher-order functions is on Saturday 1/31 in 271 Soda
- Small-group tutoring begins next week! Apply online by Sunday if you want a (free) tutor
- Homework 2 (which is small) is due Monday 2/2 at 11:59pm
- Project 1 (which is BIG) us due Thursday 2/5 at 11:59pm
- Midterm 1 on Monday 2/9 7pm-9pm
Environments for Higher-Order Functions
Environments Enable Higher-Order Functions
(Demo)
4Environment diagrams describe how higher-order functions work! Functions are first-class: Functions are values in our programming language Higher-order function: A function that takes a function as an argument value or A function that returns a function as a return value
Names can be Bound to Functional Arguments
5 Applying a user-defined function:- Create a new frame
- Bind formal parameters
(f & x) to arguments
- Execute the body:
return f(f(x)) Interactive Diagram
2 1Environments for Nested Definitions
(Demo)
Environment Diagrams for Nested Def Statements
2 1 3- Every user-defined function has
a parent frame (often global)
- The parent of a function is the
frame in which it was defined
- Every local frame has a parent
frame (often global)
- The parent of a frame is the
parent of the function called Nested def
7Interactive Diagram
How to Draw an Environment Diagram
When a function is defined: Create a function value: func <name>(<formal parameters>) [parent=<label>] Its parent is the current frame. Bind <name> to the function value in the current frame When a function is called:
- 1. Add a local frame, titled with the <name> of the function being called.
- 2. Copy the parent of the function to the local frame: [parent=<label>]
- 3. Bind the <formal parameters> to the arguments in the local frame.
- 4. Execute the body of the function in the environment that starts with the local frame.