Lecture 5 Environments
- Questions
- f2 lambda function being assigned to a parent
- Environment Diagrams
- Environment Diagrams visualize the interpreter’s process
- Code on left
- statements and expressions
- Frames on right
- Each name is bound to a value
- Names cannot be repeated in a frame
- Why use environment diagrams
- help us understand why the programs work the way they do
- Predict how a program will behave
- What we have seen so far
- Assignment Statements
- Def Statements
- Call Expressions
- Assignment Statements
- Evaluation rules
- Evaluate all expressions to the right
- Bind all values to the left names
- Calling User-Defined Functions
- Procedure
- Add a local frame
- Bind function’s formal parameters to its arguments in that frame
- Execute the body of the function in that new environment
- No new frame for built-in functions
- Function’s signature has all the information needed to create a local frame
- Frames
- keeps track of variable to value bindings
- global frame is default starting frame
- every call expression has a corresponding frame
- Parent of a function is the frame in which is was defined not called
- important for variable lookup
- How to Draw an Environment Diagram
- When a function is defined
- Create a function value: func () [parent=
- Its parent is the current frame, where function is defined
- When a function is called
- Add a local frame
- Copy the parent over
- Bind the formal parameters to the arguments
- Execute the body of the function starting with local frame
- Example
- You can override a function
- Evaluation Order
- Evaluate operator, operands, apply operator to operands
- Lambda Expressions
- square = lambda x: x*x
- lambda expression evaluates to a function
- Must be a single expression (no while loops)
- Using line numbers to identify lambda functions
- We only know of lambda’s existence at f2, so its parent is f2
- Environments Enable Higher-Order Functions
- Revisiting Evaluation Order
- Higher order functions have the same rules
- operator, operands, apply operator to operands
- Currying
- Function Currying
- Break apart a function that takes in multiple arguments, into nested functions that takes in arguments separately
- making a new higher-order function
- Can make it easier to think about one argument at a time
- Summary
- Environment diagrams to visualize and understand programming
- Diagramming follow the evluation procedure for Python
- Think deeply about how the code we write actually works
- Lambda expressions
- Similar to user-defined functions but anonymous
- Simple and can be created for one-time use or stored by assigning as an input to return a function as an output
- Currying, to make a HOF