Environments and closures
Frames, name lookup, nested functions, and closures that capture the variables around them, drawn as CS61A-style environment diagrams.
- CS61A
- Environments · Composing Programs 1.6
- Swift book
- Closures
Last lesson, makeAdder(3) returned a closure that still knew n was 3 long
after makeAdder had finished. To explain why, CS61A uses environment
diagrams: a picture of which names are bound to which values, and where
Swift looks when it meets a name.
Frames and environments
A frame is a table of bindings from names to values. The global frame holds everything bound at the top level of the program. Each call to a function creates a new local frame for its parameters and local names.
An environment is a sequence of frames. To look up a name, Swift checks the innermost frame first, then the frame it was defined in, and so on out to the global frame. The first binding found wins.
let x = 10
func f() -> Int {
let x = 20
return x
}
print(f(), x) // 20 10
Here is the diagram at the moment f returns:
Global frame
x │ 10
f │ func f() [parent = Global]
f [parent = Global]
x │ 20
Return │ 20
Inside f, the local x shadows the global one: lookup stops at the
first frame that has the name. The global x is never changed.
What would Swift print?
let n = 1
func g(_ n: Int) -> Int {
return n * 10
}
print(g(5), n)Show answer and explanation
Answer50 1
The call g(5) creates a frame where the parameter n is 5, which shadows
the global n. The body returns 50. The global n is still 1.
Drawing a diagram, step by step
CS61A draws diagrams by following a few rules, one line of code at a time. They work for Swift unchanged:
- A binding (
let,var, or assignment) writes a name and its value in the current frame. A newletorvarin an inner frame creates a new binding there, even if an outer frame has the same name. - A function definition binds the function’s name to a function value, and records the function’s parent: the frame it was defined in.
- A call creates a new frame whose parent is the function’s parent (not the caller’s frame), binds the parameters to the argument values, and runs the body there.
- A return records the return value in the frame, and execution continues where the call was made.
Rule 3 is the one that surprises people. Where a function was defined decides what it can see; where it is called does not matter.
What would Swift print?
let x = 1
func f() -> Int {
return x
}
func g() -> Int {
let x = 2
return f()
}
print(g())Show answer and explanation
Answer1
g binds its own x to 2 and calls f. But f’s parent is the global
frame, where it was defined, so the x it finds is the global one, 1.
Nested functions
A function can be defined inside another function. The inner function’s parent frame is the frame of the call that defined it, so it can use the outer function’s names:
func sumOfShifts(_ n: Int) -> Int {
func shifted(_ k: Int) -> Int {
k + n // n comes from sumOfShifts's frame
}
return shifted(1) + shifted(2)
}
print(sumOfShifts(10)) // 23
This is lexical scoping: what a name means depends on where the code is written, not on who calls it.
Closures capture
When a closure is returned from a function, the frame it was defined in does not disappear. The closure captures the names it uses and keeps them alive:
func makeCounter() -> () -> Int {
var count = 0
return {
count += 1
return count
}
}
let a = makeCounter()
print(a(), a(), a()) // 1 2 3
In diagram form, after the first call to a:
Global frame
makeCounter │ func makeCounter() [parent = Global]
a │ closure [parent = f1]
f1: makeCounter [parent = Global]
count │ 1 ← kept alive because the closure captured it
Return │ closure
Each call to makeCounter makes a new frame, so each counter gets its own
count.
What would Swift print?
func makeCounter() -> () -> Int {
var count = 0
return {
count += 1
return count
}
}
let a = makeCounter()
let b = makeCounter()
print(a(), a(), b())Show answer and explanation
Answer1 2 1
a and b come from two different calls, so they capture two different
count variables. a counts to 2 while b starts again at 1.
Closures are reference types. Binding a closure to a second name does not copy its captured state; both names refer to the same closure.
What would Swift print?
func makeCounter() -> () -> Int {
var count = 0
return {
count += 1
return count
}
}
let a = makeCounter()
_ = a()
let alsoA = a
print(alsoA(), a())Show answer and explanation
Answer2 3
a has already counted to 1. alsoA is the same closure, so calling it
gives 2, and calling a afterward gives 3.
Capturing a variable, not a value
A closure captures the variable itself, so it sees later changes. To capture the value at the moment the closure is created, list the name in a capture list in square brackets:
What would Swift print?
var x = 1
let live = { print("live", x) }
let frozen = { [x] in print("frozen", x) }
x = 2
live()
frozen()Show answer and explanation
Answerlive 2\nfrozen 1
live reads x when it runs, after x has become 2. frozen copied the
value of x into its capture list when it was created, when x was still
1.
Changing a captured variable
Assigning to a captured variable changes the variable itself, wherever it lives. Declaring a new variable with the same name inside the closure does not; it creates a new binding that shadows the outer one:
var total = 0
let addChanges = { (amount: Int) in total += amount } // changes the outer total
let addShadows = { (amount: Int) in var total = 0; total += amount } // its own total
addChanges(5)
addShadows(5)
print(total) // 5
Python needs a nonlocal declaration to change a variable from an enclosing
function; in Swift, capturing is automatic and assigning just works. The
flip side is that it is easy to change shared state without meaning to,
which is one reason Swift asks for @escaping and capture lists.
Put the lines in order
Put the lines in order so the program prints 5 15 12.
func makeAccumulator() -> (Int) -> Int {var total = 0let deposit = makeAccumulator()return { amount in}total += amountprint(deposit(5), deposit(10), deposit(-3))return total}
Show the correct program
func makeAccumulator() -> (Int) -> Int {
var total = 0
return { amount in
total += amount
return total
}
}
let deposit = makeAccumulator()
print(deposit(5), deposit(10), deposit(-3))Lab 4: Environments
Q0: What would Swift print?
What would Swift print?
var count = 0
func bump() -> Int {
count += 1
return count
}
let first = bump()
let second = bump()
print(first, second, count)Show answer and explanation
Answer1 2 2
bump changes the global count each time. The first call returns 1, the
second 2, and count itself is 2 afterward.
What would Swift print?
func outer() -> () -> Int {
var n = 10
let inner = { () -> Int in
n += 1
return n
}
n = 20
return inner
}
let f = outer()
print(f(), f())Show answer and explanation
Answer21 22
The closure captures the variable n, not its value at the time the closure
was written. By the time outer returns, n is 20, so the first call gives
21 and the next 22.
What would Swift print?
func makeAdder(_ n: Int) -> (Int) -> Int {
return { x in x + n }
}
let add5 = makeAdder(5)
let n = 100
print(add5(1))Show answer and explanation
Answer6
The global n is irrelevant. The closure’s parent is the frame of the call
makeAdder(5), where n is 5.
Q1: Draw it
Without running the code, draw the environment diagram at the moment the program prints, and say what it prints.
func makeMultiplier(_ factor: Int) -> (Int) -> Int {
return { x in x * factor }
}
let factor = 100
let triple = makeMultiplier(3)
print(triple(factor))
Show solution
It prints 300.
Global frame
makeMultiplier │ func makeMultiplier(_:) [parent = Global]
factor │ 100
triple │ closure [parent = f1]
f1: makeMultiplier [parent = Global]
factor │ 3
Return │ closure
f2: closure [parent = f1]
x │ 100
Return │ 300The argument factor in triple(factor) is looked up in the global frame,
giving 100. Inside the closure (frame f2), factor is looked up starting from
the closure’s parent, frame f1, where it is 3. The same name
means two different things in two places.
Q2: Curry
curry2 turns a two-argument function into a function that takes one
argument and returns another one-argument function: curry2(f)(x)(y) is
f(x, y).
func curry2(_ f: @escaping (Int, Int) -> Int) -> (Int) -> (Int) -> Int {
// your code here
}
Show solution
func curry2(_ f: @escaping (Int, Int) -> Int) -> (Int) -> (Int) -> Int {
return { x in
return { y in f(x, y) }
}
}
let add = curry2(+)
let addFive = add(5)
assert(addFive(3) == 8)
assert(curry2(*)(4)(5) == 20)
assert(curry2(-)(10)(3) == 7)The inner closure uses both x from its parent closure’s frame and f from
curry2’s frame. Each layer of closure adds one frame to the chain.
Q3: A Fibonacci generator
Write makeFibber(), which returns a function that returns the next
Fibonacci number each time it is called: 0, 1, 1, 2, 3, 5, …
func makeFibber() -> () -> Int {
// your code here
}
Show solution
func makeFibber() -> () -> Int {
var current = 0
var next = 1
return {
let result = current
(current, next) = (next, current + next)
return result
}
}
let fibber = makeFibber()
let firstSix = (1...6).map { _ in fibber() }
assert(firstSix == [0, 1, 1, 2, 3, 5])
let another = makeFibber()
assert(another() == 0) // a separate frame, starting over
assert(fibber() == 8) // the first fibber continuescurrent and next live in the frame of the makeFibber call and are
captured by the returned closure. They are the state that survives between
calls.
Q4: Draw it again
Draw the environment diagram for this program, up to the moment it prints, and say what it prints.
func makeCounter(start: Int) -> () -> Int {
var count = start
func next() -> Int {
count += 1
return count
}
return next
}
let c1 = makeCounter(start: 10)
let c2 = makeCounter(start: 0)
_ = c1()
print(c1(), c2())
Show solution
It prints 12 1.
Global frame
makeCounter │ func makeCounter(start:) [parent = Global]
c1 │ func next() [parent = f1]
c2 │ func next() [parent = f2]
f1: makeCounter [parent = Global]
start │ 10
count │ 12
next │ func next() [parent = f1]
Return │ func next()
f2: makeCounter [parent = Global]
start │ 0
count │ 1
next │ func next() [parent = f2]
Return │ func next()The frames for the three calls to next (two through c1, one through
c2) are omitted; each has parent f1 or f2, and changes that frame’s
count. A named nested function captures exactly like a closure expression.
Q5: A withdrawal function
CS61A’s classic: write makeWithdraw(_:), which returns a function that
withdraws from a balance it keeps track of. It returns the new balance as a
string, or "Insufficient funds" without changing anything.
func makeWithdraw(_ balance: Int) -> (Int) -> String {
// your code here
}
Show solution
func makeWithdraw(_ balance: Int) -> (Int) -> String {
var balance = balance
return { amount in
if amount > balance {
return "Insufficient funds"
}
balance -= amount
return String(balance)
}
}
let withdraw = makeWithdraw(100)
assert(withdraw(25) == "75")
assert(withdraw(25) == "50")
assert(withdraw(60) == "Insufficient funds")
assert(withdraw(50) == "0")
let another = makeWithdraw(10)
assert(another(5) == "5") // separate balancevar balance = balance makes a changeable copy of the parameter in
makeWithdraw’s frame; the returned closure captures and updates it.
Q6 (optional): Password protected
Write makeProtectedWithdraw(balance:password:). The returned function takes
an amount and a password attempt. A wrong password returns
"Incorrect password" and is remembered; after three wrong attempts the
account is frozen, and every call returns "Frozen. Attempts: " followed by
the array of wrong attempts.
Show solution
func makeProtectedWithdraw(balance: Int, password: String) -> (Int, String) -> String {
var balance = balance
var wrongAttempts: [String] = []
return { amount, attempt in
if wrongAttempts.count == 3 {
return "Frozen. Attempts: \(wrongAttempts)"
}
if attempt != password {
wrongAttempts.append(attempt)
return "Incorrect password"
}
if amount > balance {
return "Insufficient funds"
}
balance -= amount
return String(balance)
}
}
let withdraw = makeProtectedWithdraw(balance: 100, password: "hax0r")
assert(withdraw(25, "hax0r") == "75")
assert(withdraw(90, "hax0r") == "Insufficient funds")
assert(withdraw(25, "hwat") == "Incorrect password")
assert(withdraw(25, "hax0r") == "50") // a right password still works
assert(withdraw(75, "a") == "Incorrect password")
assert(withdraw(10, "hax0r") == "40")
assert(withdraw(20, "n00b") == "Incorrect password")
assert(withdraw(10, "hax0r") == "Frozen. Attempts: [\"hwat\", \"a\", \"n00b\"]")Two captured variables make up the account’s state. Each has a single place where it changes, which keeps the rules easy to check.
What’s next
Next lesson: using everything so far to design functions well, with generalization, documentation, and tests.