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

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

Lesson 3: Generics and Substitution

Lesson level: Intermediate

Purpose: Write reusable typed functions and data contracts that preserve relationships between input and output types instead of replacing precision with broad types.

Learning objectives

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

3.1 Why broad types lose information

Suppose a utility returns the first element of a list. A broad contract can say that it accepts a list and returns some value, but that description loses the essential relationship: the result has the same element type as the input list.

A generic contract introduces a type parameter—commonly written as T—to represent that relationship:

function first<T>(items: List<T>) -> T {   return items[0] }

When called with a list of strings, T becomes String. With a list of integers, it becomes Int. The body remains reusable while each call retains a precise result type.

3.2 Type parameters versus value parameters

A value parameter receives runtime data. A type parameter represents a compile-time type choice used during semantic analysis.

function repeat_value<T>(value: T, count: Int) -> List<T>

Here, T is a type parameter, while value and count are value parameters. A call supplies runtime arguments, and the checker derives or verifies the corresponding type argument.

3.3 Generic type applications

A generic type constructor becomes a concrete type when supplied with type arguments. Examples include List<String>, Map<String, Int>, and later Option<Employee> or Result<Report, Error>.

The outer name describes the shape; the arguments describe contained or related types. Different applications are distinct contracts: a list of integers is not interchangeable with a list of arbitrary mixed values merely because both are lists.

3.4 Substitution step by step

Substitution replaces every occurrence of a type parameter with one consistent type for a particular call.

Given:

function identity<T>(value: T) -> T

and the call:

let name = identity("PeaLang")

The same substitution must be applied everywhere in the signature. Treating each occurrence independently would destroy the relationship the generic declares.

3.5 Multiple occurrences create constraints

When one type parameter appears in several positions, every corresponding argument must support one consistent substitution.

function choose<T>(condition: Bool, left: T, right: T) -> T

A call with two strings can bind T = String. A call with a string and an integer creates conflicting constraints unless a documented common compatible type exists. Do not widen automatically to a vague type simply to make the call pass.

3.6 Multiple type parameters

Use separate type parameters when positions may vary independently.

function pair<K, V>(key: K, value: V) -> Map<String, V>

Each parameter has its own substitution. For a string key and integer value, the checker can derive K = String and V = Int. Reusing one parameter for unrelated roles would incorrectly require both values to share a type.

3.7 Inference from nested types

Type arguments can be inferred from inside a generic application.

function last<T>(items: List<T>) -> T

If the argument is List<Float>, matching it against List<T> yields T = Float. The return type is therefore Float.

Nested matching must preserve the outer structure. A map is not compatible with a list merely because both contain values.

3.8 Explicit type arguments

Inference is convenient when arguments provide enough evidence. Explicit type arguments are useful when the intended type cannot be derived, when an empty collection provides no element evidence, or when clarity at an API boundary matters.

Use an explicit argument only when supported by the language form and necessary for the contract. It should confirm intent, not force an incompatible value through checking.

3.9 Underdetermined type parameters

A type parameter is underdetermined when the call provides no evidence for choosing it.

function empty_list<T>() -> List<T>

Because the function receives no argument containing T, the expected result context or an explicit type argument must supply the choice. If neither does, the checker should request more information rather than guess.

3.10 What a generic body may assume

An unconstrained type parameter provides very little knowledge. A function can pass a value through, store it, return it, or place it in a compatible collection. It cannot safely assume that every T supports arithmetic, ordering, a particular property, or a domain-specific method.

function duplicate<T>(value: T) -> List<T> {   return [value, value] }

This body uses no unsupported operation on T. By contrast, value + value would require a contract proving that addition is valid.

3.11 Constrained generic behavior

When a generic algorithm needs operations beyond storage and identity, the type parameter needs an appropriate constraint. A sortable function requires ordering behavior; a formatter requires a supported display contract; a keyed utility may require a stable key representation.

State the minimum capability the algorithm needs. Overconstraining reduces reuse, while underconstraining permits operations the checker cannot justify. Structural protocols provide the project-wide mechanism for expressing these requirements and are the subject of the next lesson.

3.12 Generic collections and mutation

A typed mutable collection must preserve its element contract after creation. If a binding has type List<Int>, inserting a string violates the collection contract even if the list itself is mutable.

Mutation makes variance and compatibility especially sensitive: permitting an incompatible collection substitution can allow an invalid value to be written and later read under the wrong type. Prefer exact element contracts for mutable collections unless the language explicitly defines a safe relationship.

3.13 Generic functions versus broad functions

Compare these conceptual signatures:

function first(items: List) -> Any function first<T>(items: List<T>) -> T

The generic version preserves the input–output relationship, improves completion and diagnostics, and prevents callers from treating the result as an unrelated type. Use a broad contract only when the function truly accepts and returns unrelated dynamic values.

3.14 When not to use a generic

3.15 Generic diagnostics

Common diagnostic categories include:

Read the generic declaration, write the proposed substitution explicitly, replace every occurrence, and then recheck the resulting concrete signature. This mechanical process usually reveals the conflict.

3.16 Worked substitution table

For function select<T>(items: List<T>, index: Int, fallback: T) -> T and a call using List<String>, an integer index, and a string fallback:

PositionGeneric formAfter substitution
itemsList<T>List<String>
indexIntInt
fallbackTString
returnTString

An integer fallback would conflict with the substitution established by the list argument.

3.17 Common mistakes

3.18 Guided practice

3.19 Hands-on lab: Build a typed collection utilities module

Scenario. Create reusable utilities for lists while preserving element types.

Requirements

Acceptance criteria. Valid instantiations pass semantic checks; invalid calls fail for the intended reason; substitution tables correctly predict parameter and result types; empty and invalid indices follow explicit policies; and no utility uses a broad type where a generic relationship is available.

3.20 Review questions

3.21 Applied challenge

Refactor three duplicated utilities from earlier checkpoint projects into relationship-preserving generic functions. For each candidate, justify whether it should be generic, concrete, protocol-constrained, or represented with Option or Result. Supply substitution traces for valid calls and diagnostic analyses for two invalid calls.

Lesson summary

Generics express reusable contracts without discarding type relationships. Type parameters are bound from arguments, expected context, or explicit choices and are substituted consistently throughout a signature. Sound generic code uses only justified operations, preserves collection element contracts, reports conflicting or missing substitutions clearly, and remains concrete when reuse does not add value.

Lesson status: Ready for review.

Next: Chapter 7, Lesson 4 — Structural Protocols and Project-Wide Contracts.

← Previous Next →