13. Generics

Level: beginner · Reading time: 13 min · Prerequisite: book/chapters/13-generics.html · Track: essential · Maturity: reviewed · Last review: 2026-05-09

TL;DR (5 lines)

  • Generics justify themselves through reusable contracts.
  • The reader should see the gain, not only the syntax.
  • A tiny but real reusable helper is the best teaching unit.
  • Malformed abstractions fail at the contract boundary.
  • Use abstraction when it clarifies, not when it decorates.

Frequent mistakes

  • Adding type parameters with no real reuse benefit.
  • Teaching generic call syntax before generic design intent.
  • Mixing valid generic syntax with invalid return contracts.

Prerequisites: book/chapters/13-generics.html. See also: book/chapters/13-generics.html, book/chapters/27-grammar.html, book/chapters/31-build-errors.html.

Concrete Problem

Generic pages often show parameter syntax without explaining why a reusable contract is worth the extra abstraction.

Red Thread (Single Project)

One reusable container-like helper works for multiple element shapes while keeping the contract readable.

For what

This chapter helps the reader use abstraction only when reuse really needs it.

What you are going to do

You will inspect one generic helper, then compare it to a malformed or unnecessary abstraction.

Coherent example

space demo/generics

proc identity[T](value: T) -> T {
  give value
}

Global explanation

A generics chapter should answer one question: what reuse is being bought by the abstraction? If that answer is weak, the generic surface is probably too abstract for the reader and the code.

Invalid case

proc bad_identity[T](value: T) -> int {
  give value
}

This invalid case is intentionally small. It exists to isolate the contract failure that the chapter is trying to teach.

Common pitfalls

  • Adding type parameters with no real reuse benefit.
  • Teaching generic call syntax before generic design intent.
  • Mixing valid generic syntax with invalid return contracts.

Short exercise

Add one second generic procedure that reuses the same abstraction for a clearly different value shape.

Summary in 5 points

  1. Generics justify themselves through reusable contracts.
  2. The reader should see the gain, not only the syntax.
  3. A tiny but real reusable helper is the best teaching unit.
  4. Malformed abstractions fail at the contract boundary.
  5. Use abstraction when it clarifies, not when it decorates.

Mini quiz

  1. What contract is the coherent example trying to make explicit?
  2. Why does the invalid example fail?
  3. What boundary should remain visible if you extend the example?

See also

Next best action

Extend the coherent example by one small, justified step and keep the same contract visible from input to output.