CS61A(5): Environments

This is the lecture note of CS61A - Lecture 5.

Environments for Higher-Order Functions

Review: Higher-order function is a function that takes a function as an argument value or returns a function as a return value.

Environments for Nested Definitions

Self-reference

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Self Reference

def print_all(k):
"""Print all arguments of repeated calls.

>>> f = print_all(1)(2)(3)(4)(5)
1
2
3
4
5
"""
print(k)
return print_all

def print_sums(n):
"""Print all sums of arguments of repeated calls.

>>> f = print_sums(1)(2)(3)(4)(5)
1
3
6
10
15
"""
print(n)
def next_sum(k):
return print_sums(n+k)
return next_sum

Currying

Currying: Transforming a multi-argument function into a higher-order function with single-argument.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Currying

from operator import add, mul

def curry2(f):
"""Curry a two-argument function.

>>> m = curry2(add)
>>> add_three = m(3)
>>> add_three(4)
7
>>> m(2)(1)
3
"""
def g(x):
def h(y):
return f(x, y)
return h
return g


# Use lambda expression
curry2 = lambda f: lambda x: lambda y: f(x, y)