Skip to main content

Frame identity and lexical lookup

What this concept is​

A frame is one set of bindings plus a parent link. A closure keeps both a body and the environment in which that body was created. A call creates a new parameter frame; it does not rewrite the captured frame. The parent of that call frame is the defining environment.

Why it matters here​

A closure that escapes its creator must retain enough state to run later. Two invocations of an adder factory share code but capture distinct frames. Confusing code identity with environment identity makes callbacks accidentally share values.

Concrete example​

Let x=10; define f(y)=x+y there; then introduce a nested x=99 and call f(2). The caller frame contains 99, but the new y=2 frame points to the captured x=10 frame: the result is 12. Dynamic scope would search the caller chain and return 101. Draw these as two different arrows before opening the reference.

Common confusion / misconception​

Capturing an environment is not necessarily copying its values. This lab has no assignment, so the distinction is less visible. In a language with assignment, two closures can share one mutable location; copying a dictionary can silently change that language. Captured frames also stay reachable after a call returns.

How to use it​

Label frames G, F1, F2 and record each parent at creation time. Resolve every variable by walking only those arrows. For make(x)=lambda y:x+y, applying make(3) and make(8) creates different x frames. Calling the results with 2 yields 5 and 10.

Check yourself​

Does shadowing replace an outer binding? No: it adds a nearer binding on one lookup path. Can the call frame point at the caller? Only if you intentionally choose different scope semantics.

Mini drill or application​

Build a three-level shadowing AST. Predict the result, then alter only the call-frame parent to caller scope. Provide a case that changes and an identity-function case that does not. Explain why the unchanged case is weak evidence.

Read this only if stuck​

Draw the environment before and after each call using SICP chapter 3. Return to your own example rather than copying a book diagram.