Part I — Foundations · Chapter 4 · Lesson 3 of 5 · 10 min read
Lesson 3: Local Scope, Closures, and Higher-Order Patterns
Lesson level: Foundation
Purpose: Understand how functions resolve names, preserve surrounding values, and accept or return behavior as reusable data.
Learning objectives
By the end of this lesson, you should be able to:
- describe the local environment created for each function call;
- predict lexical name lookup across nested functions;
- distinguish local bindings, captured bindings, and global bindings;
- explain how a closure preserves access to its defining environment;
- return a function from another function;
- pass a function as an argument;
- design simple higher-order utilities;
- avoid accidental shared mutable state; and
- trace closure creation and later invocation.
1. Every call receives a local environment
When a function is called, PeaLang creates a fresh local environment for that invocation. Parameter bindings and names declared in the body belong to that environment. A second call receives a different environment, even when it invokes the same function with the same values.
Example 1 — Independent call state
function describe_order(quantity, unit_price) { let subtotal = quantity * unit_price return "{quantity} items, subtotal {subtotal}" } print(describe_order(2, 10)) print(describe_order(5, 4))
The two calls do not share quantity, unit_price, or subtotal. Each call binds its own values, computes its own result, and discards ordinary local bindings when it finishes.
2. Lexical name lookup
Name lookup follows the environment structure in which code was defined. PeaLang first checks the current local environment, then its enclosing environment, and continues outward until the name is found or lookup fails.
Example 2 — Reading an outer constant
const tax_rate = 0.18 function total_with_tax(amount) { let tax = amount * tax_rate return amount + tax }
The function finds amount and tax locally. It does not find tax_rate locally, so lookup continues outward and resolves the top-level constant.
3. Shadowing inside a function
A local declaration can use the same name as an outer binding. The nearest binding wins, so the outer value becomes hidden inside that scope.
let label = "global" function local_label() { let label = "local" return label } print(local_label()) print(label)
The function returns local; the later top-level print produces global. Shadowing is valid but should be used sparingly because readers must distinguish bindings that share a name.
4. Nested functions
A function declared inside another function can read bindings from the enclosing call. Those outer-local bindings form the nested function's lexical environment.
function build_message(prefix, name) { function render() { return "{prefix}, {name}" } return render() } print(build_message("Welcome", "Asha"))
The nested render function has no parameters, yet it resolves prefix and name from the enclosing call to build_message.
5. What a closure is
A closure is a function value paired with the lexical environment it needs. If an inner function is returned and called later, it can still access captured bindings from the outer call that created it.
Example 3 — Return a configured function
function make_multiplier(factor) { function multiply(value) { return value * factor } return multiply } let double = make_multiplier(2) let triple = make_multiplier(3) print(double(8)) print(triple(8))
The call to make_multiplier(2) returns the inner function, not the result of calling it. The returned function captures factor = 2. A separate call captures factor = 3. The resulting closures preserve independent configurations.
6. Creating versus invoking a closure
Closure creation and closure invocation happen at different times:
- Call the outer function.
- Bind its parameters and locals.
- Create the inner function with access to that environment.
- Return the function value.
- Store it under a caller-visible name.
- Invoke it later with new arguments.
- Resolve captured names through the preserved lexical environment.
In the multiplier example, factor is chosen during creation, while value is supplied during each later invocation.
7. Closures as configuration boundaries
A closure can convert repeatedly supplied configuration into a one-time setup step. The configured function then exposes a smaller, clearer interface.
Example 4 — Configure a tax calculator
function make_tax_calculator(rate) { if rate < 0 or rate > 1 { return null } function calculate(amount) { if amount < 0 { return null } return amount * rate } return calculate } let standard_tax = make_tax_calculator(0.18) print(standard_tax(500))
The outer function validates configuration once. The returned closure validates each transaction amount and reuses the captured rate.
8. Capture immutable configuration when possible
Closures are easiest to reason about when captured bindings do not change. Immutable configuration produces deterministic behavior: the same invocation input produces the same result.
Capturing mutable state can be useful for counters or stateful workflows, but it introduces history. The result of a call may then depend on how many earlier calls occurred. Use stateful closures only when that lifecycle is part of the explicit contract.
9. Functions are values
A function can be stored in a binding, passed as an argument, and returned from another function. Code that accepts or returns a function is called higher-order code.
function add_tax(amount) { return amount * 1.18 } let pricing_rule = add_tax print(pricing_rule(100))
The binding pricing_rule receives the function value. Parentheses invoke the value later.
10. Passing behavior as an argument
A higher-order function can receive a behavior and apply it to data. This separates the stable workflow from the changing rule.
Example 5 — Apply one transformation
function apply_rule(value, rule) { return rule(value) } function add_service_fee(amount) { return amount + 25 } print(apply_rule(200, add_service_fee))
apply_rule does not know the fee policy. It only knows that rule must be callable with one value and must return a compatible result. That expectation is the higher-order contract.
11. Selecting behavior
A function can return one of several function values according to policy:
function standard_discount(amount) { return amount } function gold_discount(amount) { return amount * 0.9 } function select_discount(tier) { if tier == "gold" { return gold_discount } return standard_discount } let discount_rule = select_discount("gold") print(discount_rule(500))
The selection happens once, and the returned function is invoked afterward. This pattern keeps policy selection separate from policy execution.
12. Composing small behaviors
Composition sends the result of one function into another. Small, single-purpose functions become a processing pipeline.
function apply_discount(amount) { return amount * 0.9 } function add_tax(amount) { return amount * 1.18 } function price_pipeline(amount, first_rule, second_rule) { let intermediate = first_rule(amount) return second_rule(intermediate) } print(price_pipeline(100, apply_discount, add_tax))
Order matters. Discount-then-tax may differ from tax-then-discount when policies contain thresholds or fixed charges. The pipeline contract must document sequence as well as input and output meanings.
13. Validate higher-order assumptions
Higher-order code relies on behavioral compatibility. A supplied function must accept the expected arguments, return an expected result, and avoid side effects that violate the workflow. Later typing lessons show how protocols and annotations can make these expectations explicit; foundational code must document and test them carefully.
14. Stateful closures
A closure may capture a mutable binding and update it across calls. This creates private state that is accessible only through the returned function.
Example 6 — A bounded counter
function make_counter(limit) { let count = 0 function next() { if count >= limit { return null } count += 1 return count } return next } let counter = make_counter(2) print(counter()) print(counter()) print(counter())
The closure preserves count and limit. The first two calls return 1 and 2; the third returns null. Call order is now part of the result, so the contract must describe state transitions and exhaustion.
15. Independent closure instances
Each outer call creates a separate captured environment:
let first = make_counter(2) let second = make_counter(2) print(first()) print(first()) print(second())
The two first calls advance its private count to 2. The second closure starts from its own count and returns 1.
16. Trace closures explicitly
Use two linked records:
- Closure identity: the function body and captured environment created by one outer call.
- Invocation record: current arguments, captured values before the call, local values, updates, result, and captured values after the call.
Never merge the state of separate closure instances in one trace. Distinguishing identities is essential when several configured or stateful functions exist simultaneously.
Common mistakes
- Calling a function when you mean to pass it. rule is a function value; rule() invokes it immediately.
- Returning the result instead of the inner function. A factory must return the callable when later invocation is intended.
- Assuming dynamic caller scope. Captured names come from where the function was defined, not whichever function calls it later.
- Shadowing a captured name accidentally. A nearer local binding hides the captured binding.
- Capturing mutable state without documenting history. Repeated calls may produce different results.
- Sharing one stateful closure unintentionally. Unrelated callers then affect the same captured state.
- Passing an incompatible function. The supplied behavior may expect different arguments or return an unusable value.
- Hiding important policy in anonymous configuration. Name and document configured behaviors.
- Composing functions in the wrong order. Pipeline sequence is part of the contract.
Guided practice
- Trace the environments used by total_with_tax(100).
- Explain why a local binding named tax_rate would hide the outer constant.
- Create make_adder(amount) and use it to build add-five and add-ten closures.
- Distinguish the creation-time binding from the invocation-time parameter in make_multiplier.
- Pass a validation function into apply_rule.
- Reverse the pricing pipeline and explain whether the result changes.
- Create two counters and trace their state independently.
- Rewrite a stateful closure as a stateless function when history is unnecessary.
Hands-on lab: Build configurable validation rules
Scenario. A support application validates numeric case fields against different approved ranges. Build validator factories and a higher-order evaluation workflow.
Requirements
- Create make_range_validator(minimum, maximum). Reject an invalid configuration in which minimum exceeds maximum.
- Inside the factory, create and return a function that accepts one value and returns whether it lies within the inclusive range.
- Create independent validators for service impact 0–10, affected users 0–100000, and confidence 0–1.
- Create apply_validation(value, validator) to invoke any compatible validator.
- Create all_valid(first_value, first_validator, second_value, second_validator) to combine two checks.
- Keep validators free of printing side effects; print labeled results only at the call site.
- Trace each closure's captured minimum and maximum.
- Test exact minimum, exact maximum, below-range, above-range, and ordinary values.
Extension A — Configured transformation. Build make_clamper(minimum, maximum), which returns a function that constrains a value to the configured range.
Extension B — Stateful audit counter. Build a closure that counts how many validations have been attempted and returns null after a configured maximum. Document that call order affects behavior.
Verification checklist
- Every factory validates its configuration.
- Each returned function captures only the values it needs.
- Separate factory calls create independent closures.
- Higher-order functions document the expected callable contract.
- Function values are passed without accidental invocation.
- Boundary tests prove inclusive behavior.
- Stateful behavior is isolated and explicit.
- No closure captures secrets, host objects, or unnecessary mutable state.
Deliverable. Submit the source, a closure-identity diagram, invocation traces, a boundary test matrix, output, and a short explanation of which parts are stateless and stateful.
Review questions
- What environment is created when a function is called?
- In what order does lexical name lookup search environments?
- How does shadowing affect an outer binding?
- What two components make up a closure?
- Why can a returned inner function still access an outer parameter?
- How do closure creation and invocation differ?
- What makes a function higher-order?
- What is the difference between passing rule and passing rule()?
- Why is immutable captured configuration easier to reason about?
- How do two calls to the same factory create independent state?
- What compatibility assumptions belong in a higher-order contract?
- Why is composition order part of program meaning?
Applied challenge: Configurable pricing strategy
Build a pricing system in which factories create discount and surcharge functions from validated configuration. A selector chooses a strategy for a customer tier, and a higher-order pipeline applies discount, delivery, and tax behaviors in a documented order.
Create at least three independent configured closures, including two produced by the same factory with different captured values. Add one optional stateful closure that enforces a maximum number of promotional uses. Trace closure identities, captured environments, every pipeline stage, and the stateful lifecycle.
Success criteria
- Lexical lookup is predictable and free of accidental shadowing.
- Factories reject invalid configuration before returning a function.
- Returned functions expose small, documented interfaces.
- Higher-order utilities validate their behavioral assumptions through tests.
- Separate closure instances do not share state unintentionally.
- Pipeline order is explicit and tested.
- Stateful behavior has a clear exhaustion result.
- Calculation functions remain free of unrelated output and host access.
Lesson summary
Each function call receives a fresh local environment, and lexical lookup proceeds from the current scope outward through defining environments. Closures preserve the bindings needed by returned inner functions, enabling configured and stateful behavior. Because functions are values, PeaLang code can pass, select, return, and compose behaviors. These patterns remain reliable when captures are minimal, mutable history is explicit, callable contracts are documented, and separate closure instances are traced independently.
Next lesson: Decomposition, Naming, and Error-Resistant Design
Lesson status: Approved.