---
title: "4.4 Generic kinds and constraints"
url: https://una-lang.org/en/learn/kinds/generic-kinds-and-constraints/
release: v0.4.0
edition: "0.2"
---

# 4.4 Generic kinds and constraints

## 4.4.1 What a generic kind is

Some kinds have the same shape whatever they hold. A change to a catalog entry has a value before the edit and a value after it, whether it is a price, a name or a zone. A **generic kind** is a kind with a blank in it, filled in each time the kind is used. The blank is a **type parameter**, a name for a type, written in brackets after the kind's name: `kind Change[T]`. Think of a storage box with a label "contents: ____". The box is the same; what you write on the line says what it holds.

`Change[Int]` is a change of prices, and `Change[Text]` a change of names. The type written in the brackets, `Int` or `Text`, is the **type argument**. Each type argument gives a type of its own, with `T` replaced by it.

## 4.4.2 Why generic kinds exist

Without a type parameter, each type needs its own kind, and each kind its own functions:

```una include="steps/13-no-generics/src/edits.una" title="steps/13-no-generics/src/edits.una" verified="check, run"
module edits

--- A price before and after an edit.
kind PriceChange
  before: Int
  after: Int

--- A product name before and after an edit: the same shape, for a text.
kind NameChange
  before: Text
  after: Text

--- The price edit the other way round.
undo_price(change: PriceChange) -> PriceChange = PriceChange(before: change.after, after: change.before)

--- The name edit the other way round: the same body, written again.
undo_name(change: NameChange) -> NameChange = NameChange(before: change.after, after: change.before)

pub main() -> Unit
  uses @console: Console[print]
=
  let price = undo_price(PriceChange(before: 1990, after: 1790))
  let name = undo_name(NameChange(before: "Desk lamp", after: "Reading lamp"))
  @console.print("{price}")
  @console.print("{name}")
```

`una run .` prints:

```text include="steps/13-no-generics/expected/output.txt"
PriceChange(before: 1790, after: 1990)
NameChange(before: "Reading lamp", after: "Desk lamp")
```

It works, and it is the same declaration twice and the same function twice, with only the type changed. A change of zones would need a third copy of each. A fix to one copy must be made in all of them, and the copies drift apart over time. A generic kind is written once, and works for every type.

## 4.4.3 How to write a generic kind

```una include="steps/14-generic-forms/src/forms.una#Change" title="steps/14-generic-forms/src/forms.una"
--- A value before and after an edit. `T` is the type of both.
kind Change[T]
  before: T
  after: T
```

The type parameter goes in brackets after the kind's name. Inside the declaration, `T` stands for whatever type the kind is used with, as a field's type or as part of one. Both fields have the type `T`, so the two values of one change always have the same type.

The step of this part declares three generic kinds and uses each:

```una include="steps/14-generic-forms/src/forms.una" title="steps/14-generic-forms/src/forms.una" verified="check, run"
module forms

--- A value before and after an edit. `T` is the type of both.
kind Change[T]
  before: T
  after: T

--- How many units of something: `T` is what is counted, and `units` is always an `Int`.
kind Count[T]
  item: T
  units: Int

--- A place in the warehouse and an amount kept there, each of a type of its own.
kind Slot[Place, Amount]
  place: Place
  amount: Amount

--- Whether two values differ. It is private and writes no constraint: the checker infers it.
differs[T](before: T, after: T) -> Bool = before != after

pub main() -> Unit
  uses @console: Console[print]
=
  let price: Change[Int] = Change(before: 1990, after: 1790)
  let name = Change(before: "Desk lamp", after: "Reading lamp")
  let lamps = Count(item: "LAMP-01", units: 3)
  let shelf = Slot(place: "A-4", amount: 12)
  @console.print("{price}")
  @console.print("{name.after}, {lamps.units} of {lamps.item}, shelf {shelf.place}")
  @console.print("price differs: {differs(price.before, after: price.after)}")
  let found: Option[Text] = Some("LAMP-01")
  let missing: Option[Text] = None
  @console.print("{found} {missing}")
```

```text include="steps/14-generic-forms/expected/output.txt"
Change(before: 1990, after: 1790)
Reading lamp, 3 of LAMP-01, shelf A-4
price differs: true
Some("LAMP-01") None
```

### 4.4.3.1 Fields of a fixed type next to `T`

`Count[T]` has a field `item` of type `T` and a field `units` that is always an `Int`. A generic kind may mix the two: only what varies takes the parameter.

### 4.4.3.2 Several type parameters

`Slot[Place, Amount]` takes two, separated by a comma, and its fields may have different types: `Slot(place: "A-4", amount: 12)` is a `Slot[Text, Int]`. A type parameter is often one capital letter, such as `T`, but a name that says what it stands for, such as `Place`, reads better when there are several.

### 4.4.3.3 The type argument, inferred or written

Where a value is built, the checker **infers** the type argument, which means it works the type out from the values given: `Change(before: "Desk lamp", after: "Reading lamp")` is a `Change[Text]`. You can also write it, in a type: `let price: Change[Int] = …` says what `price` holds, and the checker holds the value to it.

### 4.4.3.4 Generic sums

A sum can take a type parameter too. `Option[T]`, a value that may be missing, is one that every module has: `Some(value)` holds a `T`, and `None` holds nothing. `Some("LAMP-01")` is an `Option[Text]`, as the last line of the output shows. [Section 7.1](https://una-lang.org/en/learn/failure/a-value-that-may-be-missing-option/#s7-1) teaches `Option` in full.

## 4.4.4 Generic functions and their constraints

A function can take type parameters too, written in brackets after its name: `undo[T](change: Change[T]) -> Change[T]` works on a change of any type. Inside it, `T` is a type the function knows nothing about. It can move values of `T` around, put them in fields, and give them back, but not compare them, since some types cannot be compared.

A **constraint** says what the function needs from `T`, and in exchange limits the types it accepts. It is written after the parameter, with a colon: `changed[T: Eq]`. Una has three, each including the one before. The **fixed-width integers** in the table are the types such as `U8` and `I32` of [section 2.3](https://una-lang.org/en/learn/numbers/fixed-width-integers/#s2-3), and `x.to_int()` turns one into an `Int`:

| Constraint | Allows on values of `T` | Satisfied by |
| --- | --- | --- |
| `Eq` | `==`, `!=`, and interpolation | every type whose values hold no functions |
| `Ord` | what `Eq` allows, and `<`, `<=`, `>`, `>=` | `Int`, the fixed-width integers, `Text`, and sums whose variants have no fields |
| `Integer` | what `Ord` allows, and `x.to_int()` | `Int` and the fixed-width integers |

A record or a sum is `Eq` when its values hold no functions, and only a sum without fields is `Ord`. A function as a value comes in [chapter 10](https://una-lang.org/en/learn/collections/functions-as-values-and-lambdas/#s10-2); every type of this chapter is `Eq`.

> [!NOTE]
> Constraints exist from edition 0.2 on, the edition of every package in this book. In edition 0.1, a type parameter takes no constraint, and the checker works out on its own whether a function compares values of `T`.

## 4.4.5 Undoing and comparing changes

The module `changes` declares `Change[T]` and three generic functions over it, with three levels of need:

:::steps
```una include="steps/15-generics/src/changes.una" title="steps/15-generics/src/changes.una" verified="check, run"
module changes

kind Zone = Local | National | Abroad

--- A value before and after an edit to a catalog entry. `T` is any type.
kind Change[T]
  before: T
  after: T

--- The edit the other way round. It works for every `T`, since it only moves values.
undo[T](change: Change[T]) -> Change[T] = Change(before: change.after, after: change.before)

--- Whether the edit changed anything. `!=` needs values that can be compared: `Eq`.
changed[T: Eq](change: Change[T]) -> Bool = change.before != change.after

--- The larger of the two values. `>` needs values with an order: `Ord`.
larger[T: Ord](change: Change[T]) -> T = if change.after > change.before then change.after else change.before

pub main() -> Unit
  uses @console: Console[print]
=
  let price = Change(before: 1990, after: 1790)
  let name = Change(before: "Desk lamp", after: "Desk lamp")
  let zone = Change(before: Local, after: Abroad)
  @console.print("{undo(price)}")
  @console.print("price changed: {changed(price)}, name changed: {changed(name)}")
  @console.print("larger price {larger(price)}, farther zone {larger(zone)}")
  let label = Change(before: "desk lamp", after: "Desk lamp")
  @console.print("{changed(label)} {larger(label)}")
```

1. **`kind Change[T]`.** A record with a type parameter. Both fields have the type `T`, so a change from a price to a name cannot be built.
2. **`undo[T]`.** No constraint is needed: `undo` only swaps the two values.
3. **`changed[T: Eq]`.** `!=` compares two values of `T`, so `T` must be `Eq`.
4. **`larger[T: Ord]`.** `>` needs an order, so `T` must be `Ord`: `Int`, `Text`, the fixed-width integers, and sums whose variants have no fields. `Zone` is one, so `larger(zone)` gives the farther zone.
5. **`Change(before: 1990, after: 1790)`.** `T` is inferred as `Int` here, `Text` for `name` and `Zone` for `zone`.
:::

`una run .` prints, among other lines:

```text include="steps/15-generics/expected/output.txt#L1-L3"
Change(before: 1790, after: 1990)
price changed: true, name changed: false
larger price 1990, farther zone Abroad
```

## 4.4.6 How generics behave

### 4.4.6.1 One type per parameter, in every field

A type parameter stands for one type in each value. Build a `Change` with a text before and a number after:

```diff include="steps/14-generic-forms..steps/16-mixed-change:src/forms.una" title="src/forms.una" context="0"
--- a/src/forms.una
+++ b/src/forms.una
@@ -25 +25 @@
-  let name = Change(before: "Desk lamp", after: "Reading lamp")
+  let name = Change(before: "Desk lamp", after: 1790)
```

```text include="steps/16-mixed-change/expected/rendered.txt"
[U2001] Error: field `after` of `Change` must be `Text`, found `Int`
    ╭─[ src/forms.una:25:49 ]
    │
 25 │   let name = Change(before: "Desk lamp", after: 1790)
    │                                                 ──┬─
    │                                                   ╰─── field `after` of `Change` must be `Text`, found `Int`
    │
    │ Note: run `una explain U2001` for an explanation
────╯
```

The checker took `T` from the first field, `Text`, so the second must be a `Text` as well, and the marks point at `1790`.

### 4.4.6.2 An operator needs its constraint

In a public function, `==` or interpolation on values of `T` without the constraint `Eq` is U2026, and its repair writes the constraint: [A public generic function without its constraint](https://una-lang.org/en/learn/kinds/common-mistakes/#a-public-generic-function-without-its-constraint-u2026) shows it. Arithmetic is never allowed on `T`, with a constraint or without: `a + b` on two values of a `T: Integer` is U2001, "an operand of `+` must be `Int`, found `T`". Turn them into `Int` with `to_int()`, and add those.

### 4.4.6.3 A call passes a type that satisfies it

At each call, the type argument must satisfy the constraint. Pass `larger` a change of shelves, a record:

```diff include="steps/15-generics..steps/17-constraint-rules:src/changes.una" title="src/changes.una" context="0"
--- a/src/changes.una
+++ b/src/changes.una
@@ -3,0 +4,5 @@
+
+--- A shelf of the warehouse: a record, which has no order.
+kind Shelf
+  aisle: Int
+  level: Int
@@ -29,0 +35,2 @@
+  let moved = Change(before: Shelf(aisle: 4, level: 1), after: Shelf(aisle: 2, level: 3))
+  @console.print("{larger(moved)}")
```

```text include="steps/17-constraint-rules/expected/rendered.txt#L1-L6"
[U2025] Error: `larger` needs its type parameter `T` to satisfy `Ord`, and `Shelf` does not
    ╭─[ src/changes.una:36:20 ]
    │
 36 │   @console.print("{larger(moved)}")
    │                    ──────┬──────
    │                          ╰──────── `larger` needs its type parameter `T` to satisfy `Ord`, and `Shelf` does not
```

The error is at the call, U2025, and names the three things involved: the function, `larger`, its constraint, `Ord`, and the type that does not satisfy it, `Shelf`. A record has no order, so there is no larger shelf. Compare the fields you mean, such as `aisle`, with a function written for shelves.

### 4.4.6.4 Constraints go on functions, not on kinds

A kind's type parameters take no constraint: `kind Change[T: Eq]` does not parse, U0101, "unexpected `:`". The kind only holds values; the functions that compare them state what they need. A name other than `Eq`, `Ord` or `Integer` after the colon is U2027, "`Same` is not a constraint".

### 4.4.6.5 A private function's constraint is inferred

A function without `pub` may leave its constraint out, and the checker infers the least one its body needs, as it works out such a function's `uses` ([section 6.3](https://una-lang.org/en/learn/functions/what-a-header-says-pub-private-functions-and-inferred-headers/#s6-3)). `differs`, in the step of [How to write a generic kind](#how-to-write-a-generic-kind), compares with `!=` and writes no constraint. `una contract`, which prints a function's header as the checker sees it, shows what it inferred:

```sh
una contract forms.differs
```

```text include="steps/14-generic-forms/expected/commands/contract.txt#L3"
differs[T: Eq](before: T, after: T) -> Bool -- inferred
```

A `pub` function writes its constraints, since callers in other modules rely on its header. Apart from `differs`, which shows the rule, this book writes them on every function, as it writes every `uses` line.

## 4.4.7 The weakest constraint the body needs

:::decide
**Which to use:**

| The body… | Write |
| --- | --- |
| Only moves values of `T`: stores, swaps, gives them back | `[T]`, no constraint |
| Compares values with `==` or `!=`, or puts them in a text | `[T: Eq]` |
| Orders values with `<`, `<=`, `>` or `>=` | `[T: Ord]` |
| Needs the number, with `to_int()` | `[T: Integer]` |
| Works on one type only | No type parameter: name the type |
:::

Write the weakest constraint the body needs. `undo` needs none, so it works on a `Change` of any type. `changed` needs `Eq`, and `larger` needs `Ord`, which also gives `Eq`. A stronger constraint than the body uses only refuses callers for no reason.

## 4.4.8 Check yourself: generics

`main` ends with a change of a product name that only changes one letter from small to capital:

```una include="steps/15-generics/src/changes.una#L28-L29" title="steps/15-generics/src/changes.una"
  let label = Change(before: "desk lamp", after: "Desk lamp")
  @console.print("{changed(label)} {larger(label)}")
```

Does `changed(label)` say `true` or `false`, and which name does `larger(label)` give?

:::answer Show the answer
```text include="steps/15-generics/expected/output.txt#L4"
true desk lamp
```

`"desk lamp"` and `"Desk lamp"` are different texts, since `==` compares them character by character, so the change counts. `Text` is ordered character by character too, by each character's number in Unicode, where the capital letters `A` to `Z` come before the small letters `a` to `z`. `d` comes after `D`, so `"desk lamp"` is the larger.
:::
