PeaBox Lab › PeaLang › Learn › Chapter 4 › Lesson 3

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:

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:

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:

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

Guided practice

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

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

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

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

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.

← Previous Next →