CS61A lect5

Environments for Higher-Order Functions

1
2
3
4
5
def apply_twice(f, x):
return f(f(x))
def square(x):
return x * x
result = apply_twice(square, 2)

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
2
3
4
5
def make_adder(n):
def adder(k):
return k+n
return adder
add_three=make_adder(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
How to Draw an Environment Diagram
When a function is defined:
Create a function value: func () [parent=

  1. Add a local frame, titled with the of the function being called.
    2. Copy the parent of the function to the local frame: [parent=
  2. Bind the to the arguments in the local frame.
  3. Execute the body of the function in the environment that starts with the local frame.
    Local Names are not Visible to Other (Non-Nested) Functions
    1
    2
    3
    4
    def composel(f,g):
    def h(x):
    return f(g(x))
    return h
    Self-Reference:Returning a Function Using Its Own Name
    1
    2
    3
    4
    def print_all(x):
    print(x)
    return print_all
    print_all(1)(2)(3)
    1
    2
    3
    4
    5
    def print_sum(x)
    print(x)
    def nect_sum(y):
    return print_sum(x+y)
    return next_sum
    Function Currying
    Curry: Transform a multi-argument function into a single-argument, higher-order function