PeaBox Lab › PeaLang › Learn › Chapter 7 › Lesson 2

Part II — Intermediate Development · Chapter 7 · Lesson 2 of 7 · 9 min read

Lesson 2: Inference, Compatibility, and Gradual Adoption

Lesson level: Intermediate

Purpose: Understand how PeaLang derives types from context, decides whether values satisfy declared contracts, and strengthens existing programs without requiring an all-at-once migration.

Learning objectives

By the end of this lesson, you should be able to:

2.1 Why inference matters

Annotations communicate contracts explicitly, but repeating an obvious type at every local binding can obscure the program’s real logic. Type inference lets semantic analysis derive useful information from literals, expressions, assignments, function signatures, and control flow.

let quantity = 3 let unit_price = 12.5 let subtotal = quantity * unit_price

The initializer establishes useful type information for each binding without requiring a written annotation. The checker can then analyze later operations against those inferred types.

Design principle. Prefer explicit contracts at important boundaries and inference for obvious implementation details.

2.2 Sources of inferred information

Inference should remain explainable. If a type depends on distant or conflicting evidence, add an annotation at the point where the intended contract becomes meaningful.

2.3 Declared types constrain inference

An explicit annotation is not a suggestion for the checker to replace. It states the intended contract, and the initializer must be compatible with it.

let retries: Int = 3 let label: String = "pending" let enabled: Bool = true

If an initializer conflicts with the annotation, investigate whether the data, annotation, or domain model is wrong. Do not broaden the annotation merely because the current expression is inconvenient.

2.4 Compatibility in assignments

Assignment is valid when the new value satisfies the existing binding contract. An inferred binding also establishes expectations from its initializer.

let attempts = 0 attempts += 1 attempts = "one" // incompatible

Compatibility prevents a name from changing meaning unpredictably. A variable called attempts should not begin as a counter and later become a message.

2.5 Compatibility in function calls

Each argument is checked against its corresponding parameter contract.

function repeat(message: String, count: Int) -> String {   return std.string.repeat(message, count) } let banner = repeat("Ready", 3) let invalid = repeat(3, "Ready") // both arguments conflict

Named parameters, defaults, and higher-order uses introduce additional constraints, but the central question remains: can the supplied value safely satisfy the parameter’s declared role?

2.6 Compatibility in return paths

Every reachable normal return must satisfy the function’s result contract.

function response_minutes(priority: String) -> Int {   if priority == "critical" { return 15 }   if priority == "high" { return 60 }   return 480 }

A branch returning "unknown" would violate the contract. If failure is a legitimate outcome, model it explicitly rather than mixing an error sentinel into the success type.

2.7 Branch joins and mixed paths

When control flow can produce different values for one binding, the checker must find a compatible result for every reachable path.

let label = "standard" if security_relevant {   label = "critical" } else {   label = "ordinary" }

Both paths preserve the string contract. If one path assigned a number, the join would expose a conflict. Use separate variables or a deliberate union-like model only when the domain truly permits multiple forms.

2.8 Widening and narrowing

Widening accepts a broader set of values; narrowing establishes a more specific contract. Widening can improve interoperability when it reflects the real domain, but it also removes guarantees. Narrowing can improve safety only when supported by validation, flow evidence, or an explicit conversion.

Do not confuse numeric compatibility with arbitrary coercion. A checker may permit documented compatible numeric use while still rejecting strings, booleans, or null. Never assume that a type mismatch will be repaired automatically at runtime.

2.9 Unknown information and gradual boundaries

Gradual typing must represent places where complete static knowledge is unavailable: unannotated legacy functions, dynamically shaped host data, optional integrations, or values produced across an untyped boundary. Unknown information should be contained rather than allowed to spread silently through the project.

Place an explicit typed adapter around an uncertain boundary:

This adapter pattern lets old and new code coexist while making uncertainty visible at a small number of locations.

2.10 A staged adoption plan

Migrate one coherent slice at a time. A slice might be one exported function and its direct helpers, not an arbitrary number of files.

2.11 Preserving compatibility for existing callers

Adding annotations can reveal that callers already pass inconsistent values. Decide whether the existing behavior is valid compatibility or an undocumented defect.

Compatibility is a product decision, not permission to accept every historic value forever.

2.12 Reading inference diagnostics

A diagnostic may originate where incompatible evidence meets rather than where the wrong value was created. Trace the value backward to its declaration, branch, call, or boundary.

Use this sequence:

When many diagnostics appear after one annotation, group them by root cause. A single imprecise boundary or inconsistent return path can create several downstream messages.

2.13 Inference does not replace design

The checker can derive relationships present in the program, but it cannot invent missing domain meaning. A number may represent currency, percentage, count, duration, or identifier. Clear names, documented units, structured types, and runtime rules remain necessary.

Inference should reduce repetition, not hide intent. Add an annotation when it marks an architectural boundary, prevents a dangerous ambiguity, or makes a contract easier to review.

2.14 Worked migration example

Consider an untyped pricing function used by both a command-line script and a host application:

function calculate_total(quantity, unit_price, discount) {   return quantity * unit_price - discount }

A safe migration proceeds as follows:

The annotation phase should not change pricing policy. It should make the existing contract explicit and expose unsupported variations.

2.15 Common mistakes

2.16 Guided practice

2.17 Hands-on lab: Gradually type the pricing rules library

Scenario. Strengthen the Chapter 4 pricing library while preserving its established outputs and untyped host-facing input format.

Requirements

Required test groups: ordinary pricing, zero quantity, exact discount boundary, invalid negative values, missing fields, incompatible field types, legacy caller format, and typed direct calls.

Acceptance criteria. Semantic checks pass after deliberate defects are removed; all valid baseline tests remain unchanged; invalid boundary data is rejected explicitly; uncertainty is confined to the adapter; and the migration note describes compatibility decisions.

2.18 Review questions

2.19 Applied challenge

Select one earlier checkpoint project and create a three-stage typing roadmap. For each stage, name the functions and boundaries to strengthen, the diagnostics expected, the compatibility risks, the runtime validators retained, and the tests that prove unchanged behavior. Implement the first stage and report any defect exposed by inference or compatibility checking.

Lesson summary

Type inference reduces repetitive annotations by deriving information from literals, expressions, assignments, calls, branches, and interfaces. Compatibility rules keep assignments, arguments, and returns aligned with their contracts. Gradual adoption succeeds when teams establish a behavioral baseline, type stable boundaries first, contain uncertain data behind validated adapters, resolve diagnostics by root cause, and preserve tests and supported callers.

Lesson status: Ready for review.

Next: Chapter 7, Lesson 3 — Generics and Substitution.

← Previous Next →