CS 61A lect5
CS61A lect5
Environments for Higher-Order Functions
1 | def apply_twice(f, x): |
Applying a user-defined function:
• Create a new frame
• Bind formal parameters (f & x) to arguments
• Execute the body: return f(f(x))
Nested Def Statements
1 | def make_adder(n): |
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
How to Draw an Environment Diagram
When a function is defined:
Create a function value: func
- Add a local frame, titled with the
of the function being called.
2. Copy the parent of the function to the local frame: [parent= - Bind the
to the arguments in the local frame. - Execute the body of the function in the environment that starts with the local frame.
Local Names are not Visible to Other (Non-Nested) FunctionsSelf-Reference:Returning a Function Using Its Own Name1
2
3
4def composel(f,g):
def h(x):
return f(g(x))
return h1
2
3
4def print_all(x):
print(x)
return print_all
print_all(1)(2)(3)Function Currying1
2
3
4
5def print_sum(x)
print(x)
def nect_sum(y):
return print_sum(x+y)
return next_sum
Curry: Transform a multi-argument function into a single-argument, higher-order function
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
