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:
- explain the problem generics solve;
- distinguish a type parameter from an ordinary value parameter;
- read generic function and collection contracts;
- derive type arguments from a call;
- apply substitution consistently through a signature;
- identify conflicting or underdetermined substitutions;
- choose between a generic contract and a concrete overload or function;
- preserve type relationships across reusable utilities; and
- diagnose common generic-call failures.
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 argument has type String.
- The parameter requires type T.
- The checker binds T = String.
- The instantiated parameter becomes String.
- The instantiated return type also becomes String.
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
- Use a concrete function when the operation is meaningful for one domain type only.
- Use separate functions when behaviors differ substantially rather than sharing one algorithm.
- Use a protocol constraint when reuse depends on named behavior.
- Use Option or Result when the issue is absence or failure, not type variability.
- Avoid a type parameter that appears only once and preserves no useful relationship.
- Do not expose internal complexity through a generic public API without a real caller need.
3.15 Generic diagnostics
Common diagnostic categories include:
- Conflicting substitution: one type parameter is forced to incompatible types.
- Cannot infer type argument: insufficient evidence exists.
- Wrong number of type arguments: the application does not match the declaration.
- Constraint not satisfied: the chosen type lacks required behavior.
- Generic structure mismatch: outer constructors such as List and Map differ.
- Invalid operation on type parameter: the body assumes unsupported behavior.
- Return substitution mismatch: the implementation returns a value incompatible with the instantiated result.
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:
| Position | Generic form | After substitution |
|---|---|---|
| items | List<T> | List<String> |
| index | Int | Int |
| fallback | T | String |
| return | T | String |
An integer fallback would conflict with the substitution established by the list argument.
3.17 Common mistakes
- Using a broad type instead of a relationship. Preserve connections between inputs and outputs with type parameters.
- Substituting occurrences independently. One type parameter has one consistent choice per instantiation.
- Reusing one parameter for unrelated roles. Introduce independent parameters when types may vary separately.
- Assuming operations on unconstrained T. Add the minimum justified constraint.
- Forcing explicit arguments over conflicts. Explicit syntax cannot make incompatible values safe.
- Ignoring empty-collection ambiguity. Supply expected context or an explicit type choice.
- Treating mutable collections as freely interchangeable. Preserve safe element contracts.
- Adding generics without reuse. Concrete domain functions are often clearer.
- Confusing generic variation with absence or failure. Use the appropriate Option or Result model.
3.18 Guided practice
- Substitute T = Int through function identity<T>(value: T) -> T.
- Infer the result type of first for lists of strings, floats, and booleans.
- Find the conflict in choose(true, "yes", 0).
- Decide whether two positions need one shared type parameter or two independent parameters.
- Explain why an empty generic collection may need expected context.
- Identify an invalid operation inside an unconstrained generic body.
- Compare a broad utility signature with a relationship-preserving generic version.
- Decide whether a domain-specific pricing function should be generic.
3.19 Hands-on lab: Build a typed collection utilities module
Scenario. Create reusable utilities for lists while preserving element types.
Requirements
- Implement conceptual generic contracts for identity, first, last, choose, repeat-value, and select-with-fallback.
- Document every type parameter and the relationship it preserves.
- Use at least two functions with multiple occurrences of one parameter.
- Use one function with two independent type parameters.
- Test each utility with strings, integers, and one structured portable value.
- Create an empty-input policy that does not hide absence with an arbitrary sentinel.
- Introduce conflicting substitutions, missing inference evidence, wrong type-argument counts, and invalid body operations.
- Record the expected and actual diagnostics.
- Confirm that returned values retain precise types at call sites.
- Keep runtime bounds checks for indexing despite static typing.
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
- What information does a generic type parameter preserve?
- How does a type parameter differ from a value parameter?
- What does substitution do to a generic signature?
- Why must every occurrence of one parameter receive the same substitution?
- When are multiple type parameters necessary?
- How can a type argument be inferred from a nested collection type?
- Why can an empty generic result be underdetermined?
- What operations are safe on an unconstrained type parameter?
- Why are mutable generic collections sensitive to unsafe compatibility?
- When is a concrete function clearer than a generic one?
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.