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

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

Lesson 1: Variable, Parameter, and Return Annotations

Level: Intermediate

Purpose. Learn to document and check value contracts without giving up PeaLang’s gradual, practical programming model.

Learning objectives

1.1 The optional-typing mental model

PeaLang permits useful programs to remain unannotated while allowing developers to state stronger contracts where clarity and tooling matter. An annotation records the set of values a program location is intended to accept or produce. Semantic analysis compares operations and value flow with that declared intent before execution.

Annotations improve documentation, editor assistance, refactoring confidence, and early diagnostics. They do not sanitize external input, grant capabilities, enforce resource budgets, or prove every runtime property. Data from files, networks, command-line arguments, and host applications must still be validated when it enters the trusted program.

Guiding rule. Use annotations to describe trusted program contracts; use runtime validation to establish that untrusted data satisfies those contracts.

1.2 Variable annotations

A variable annotation states the intended type of values assigned to a binding. The declaration keeps its ordinary initialization behavior while adding a contract for semantic analysis.

Illustrative syntax

let quantity: Int = 12 let unit_price: Float = 4.75 const currency: String = "USD" let active: Bool = true

The checker can report assignments that contradict the declared type:

let quantity: Int = 12 quantity = "twelve" // type mismatch

Prefer annotations on stable domain concepts, public module state, values whose initial expression is ambiguous, and locations where a later accidental reassignment would be costly. Local values with obvious initializers may remain unannotated when inference communicates the contract clearly.

1.3 Parameter annotations

Parameter annotations define the input contract at a function boundary. They help callers understand permitted arguments and allow semantic analysis to trace incompatible calls.

function subtotal(quantity: Int, unit_price: Float) -> Float {   return quantity * unit_price }

The annotation says that quantity is an integer, unit_price is a floating-point value, and the function promises a floating-point result. A call such as subtotal("3", 8.5) should be diagnosed because a string does not satisfy the first parameter contract.

Annotate parameters at reusable boundaries: exported functions, callbacks, domain services, collection transforms, host entry points, and functions with several similar-looking arguments. Good parameter names still matter; types complement names rather than replacing them.

1.4 Return annotations

A return annotation describes every normal value-producing exit from a function. The checker compares each reachable return path with the declared result.

function format_sku(prefix: String, number: Int) -> String {   return prefix + "-" + str(number) }

A declared return type makes incomplete branches and inconsistent outcomes easier to detect:

function discount_rate(tier: String) -> Float {   if tier == "gold" { return 0.20 }   if tier == "silver" { return 0.10 }   return "none" // type mismatch }

For procedures that intentionally produce no useful value, use the language’s no-result convention rather than inventing a sentinel. Keep absence as a domain choice distinct from a function that merely performs an action.

1.5 Complete function contracts

A complete signature lets readers reason about a function without inspecting its body. The strongest annotations usually belong at module boundaries, while implementation-local details can rely more heavily on inference.

function price_line(quantity: Int, unit_price: Float, taxable: Bool) -> Float {   let base: Float = quantity * unit_price   if taxable { return base * 1.18 }   return base }

Review a signature as a contract: Are argument types precise? Is absence represented intentionally? Does every path return the promised type? Could a caller satisfy the declared types yet still violate a business rule? If so, add runtime validation for that rule.

1.6 Nullable and alternative values

When a value may be absent or may legitimately take more than one form, express that possibility explicitly with the supported optional or union construct rather than silently relying on null. The exact contract should match the domain: “missing” is different from zero, an empty string, an empty list, or an error result.

Before widening a type, ask why alternatives exist. If they represent separate outcomes, a structured Option or Result contract is often clearer than a broad union. Later lessons develop those types in depth.

1.7 Static contracts versus runtime validation

Suppose a host sends a portable map containing quantity and unit_price. A typed function can declare what it expects after conversion, but the incoming map is still data, not proof.

function checked_subtotal(record: Map) -> Float {   assert_required(record, ["quantity", "unit_price"])   let quantity: Int = require_positive_int(record["quantity"])   let unit_price: Float = require_nonnegative_number(record["unit_price"])   return subtotal(quantity, unit_price) }

The annotations protect internal value flow. The validators protect the trust boundary. Both are necessary.

1.8 Gradual adoption strategy

Avoid a mechanical “annotate everything” campaign. A gradual program should remain executable while its contracts become stronger. Do not weaken precise types merely to silence diagnostics; instead, investigate whether the code, annotation, or domain model is wrong.

1.9 Reading type diagnostics

A useful diagnostic identifies the expected type, the actual type, and the relevant source location. Read from the earliest mismatch outward: later errors may be consequences of the first incompatible assignment, argument, or return.

Use this repair sequence: state the intended contract, inspect the value’s origin, verify every branch, fix the narrowest cause, then rerun semantic checks and tests. Never insert arbitrary conversions merely to satisfy the checker; conversion should represent a deliberate domain rule.

1.10 Common mistakes

1.11 Guided practice: annotate a pricing module

Start with an unannotated module containing subtotal, discount, tax, and total. For each function:

Expected observation. Types can detect incompatible value flow, while tests and validation remain responsible for pricing rules such as nonnegative amounts and allowed discount ranges.

1.12 Hands-on lab: typed inventory valuation

Scenario. Extend the Chapter 5 inventory analyzer with typed internal functions while preserving its portable host boundary.

Requirements

Acceptance criteria. Semantic checks pass after the deliberate defects are repaired; existing inventory results remain unchanged; invalid external records are rejected by validation; and exported results contain only portable values.

1.13 Review questions

1.14 Applied challenge

Choose a small untyped module from an earlier checkpoint. Produce a typed public interface, explain each annotation, retain the necessary runtime validators, and write a short compatibility note for existing callers. Demonstrate one defect caught by semantic analysis and one defect that only runtime validation or testing can catch.

Lesson summary

Optional annotations let PeaLang programs state stronger contracts for variables, parameters, and return values while remaining compatible with gradual adoption. Use those contracts to improve semantic diagnostics and maintainability, but continue validating untrusted data and testing domain behavior.

Lesson status: Ready for review.

Next: Chapter 7, Lesson 2 — Inference, Compatibility, and Gradual Adoption.

← Previous Next →