Skip to content

4. Types

Every declared type is named. Four keywords declare types:

  • struct declares a nominal record type with named fields (Structs).
  • enum declares a nominal sum type (Enums (Algebraic Data Types)).
  • type declares a distinct type over another type, or a zero-sized type (Distinct Types).
  • typealias declares another name for an existing type (Type Aliases).

A type body holds only its fields or variants. Functions and once values a type owns go in an inherent impl Type block, interface implementations in impl Iface for Type blocks, and derived ones in derive Iface for Type declarations, all at top level beside the type (§12).

A type’s name may be a dotted PascalCase path when the type belongs under a parent type: type Civil.Days Int declares the type Civil.Days. It is a declaration of its own, not an item inside Civil, and Civil must be in scope. Construction, destructuring, derives, owner calls and impls all use the full name, which is the type’s identity.

struct Civil end

type Civil.Days Int

fn days_value(days: Civil.Days) -> Int
    Civil.Days(n) = days
    n
end

fn main()
    dbg days_value(Civil.Days(3)) // 3
end

Taught in Scalars & Strings.

The primitive types are Int, Float, Decimal, Bool, String, Codepoint, Byte and Unit. Each implements Display and Debug except as noted (§12).

Int is the one integer type: signed and exact at any size, with no largest or smallest value. There are no sized or unsigned variants. Arithmetic never overflows; the value grows (§8). Where an Int meets a fixed number of bits (a Go binding, a database column), a value that does not fit is an error there. The bitwise operators work on Ints of any size (§8).

Float is IEEE 754 binary64, including its special values (Float Special Values).

Decimal is an exact base-10 number of any precision, a mantissa and a scale. It takes part in the arithmetic and comparison operators like Int and Float.

  • +, - and * never round; the scale grows as needed (1.50d * 1.5d == 2.250d). Rounding happens only in functions that name a RoundingMode (std::decimal). There is no global precision or rounding context.
  • / rounds a quotient that does not end to 34 significant digits, half-even (10d / 3d is 3.333333333333333333333333333333333d), and an exact quotient keeps its smallest scale (10.00d / 4d is 2.5d). §8 Decimal arithmetic gives the rule.
  • Decimal has no NaN and no infinities. / and % take a NonZeroDecimal divisor, as Int’s take a NonZeroInt, so a divisor that may be zero is a compile error (§8 Decimal arithmetic).
  • The scale shows in display (1.50d prints 1.50) but not in equality: ==, Comparable, Hashable and patterns compare by value, so 1.50d == 1.5d and the two are one map key.

Bool is the enum of True and False.

Unit is the type of a function with no meaningful result, and has one value, Unit. A function with no -> result returns Unit. Unit works as a type argument (Result<Unit, String>). It implements Equatable and Hashable, and neither Display nor Comparable.

Infallible has no values. Result<T, Infallible> is a result that is never an Err. It implements Display, Equatable and Hashable, and std/http’s ToResponse, whose functions can never be called, so a bound such as where T: Hashable accepts a Result<Int, Infallible>. It is what a lambda’s result leaves open against an interface (§7 Lambdas).

Codepoint is a Unicode scalar value, with a literal for ASCII (§3 Codepoint literals). There is no character type: one character of text is a String of length 1.

Byte is a value from 0 to 255, and Bytes an immutable byte sequence, the boundary type for Go’s []byte. Byte is not a number: it has no arithmetic (b + 1 is no impl of `Add` for `Byte` (required via add operator `+`)), and Byte.to_int and Int.to_byte convert. An integer literal where a Byte is expected is a Byte (§3 Byte literals). Bytes + Bytes concatenates.

Taught in Scalars & Strings.

A String is UTF-8 text, always. It is a sequence of graphemes, the characters a reader sees: String.length counts graphemes, and a String iterates by grapheme. Its bytes and codepoints are reached through String.to_bytes and String.to_codepoints.

fn main()
    dbg String.length("café")               // 4
    dbg Iter.to_list("café")                // ["c", "a", "f", "é"]
    dbg String.length("👨‍👩‍👧")                 // 1
    dbg Iter.count(String.to_bytes("café")) // 5
end

Equality, hashing and ordering compare the UTF-8 bytes, with no normalization; byte order is codepoint order. A precomposed "é" (U+00E9) and a decomposed "e" followed by U+0301 are one grapheme each and are not ==. String.normalize converts between forms. The functions over strings are in std::strings.

A Float may be NaN, +Infinity or -Infinity. They are values of Float, produced by IEEE 754 arithmetic and by Float.nan(), Float.positive_infinity() and Float.negative_infinity().

Float division by zero does not trap: it gives the IEEE value. Int division takes a NonZeroInt divisor, since every Int is a number and none can stand for the missing result, so a divisor that may be zero is a compile error (§8 Integer division and remainder).

fn main()
    dbg 1.0 / 0.0               // +Inf
    dbg -1.0 / 0.0              // -Inf
    dbg Float.is_nan(0.0 / 0.0) // True
end

NaN and the infinities pass through arithmetic and rounding as IEEE 754 says. -0.0 and 0.0 are two values that are ==. How ==, compare and < treat NaN is §5 Equality and Ordering Semantics. No Float function traps on a NaN operand. The functions over floats are in std::float.

Taught in Collections.

The built-in types are immutable: every operation on a value returns a new value.

  • Maybe<T>, Some(value) or None, and Result<T, E>, Ok(value) or Err(error), are enums (§11).
  • List<T>, Vector<T>, Map<K, V> and Set<T> are the collections (below).
  • Range<T> is a range of a Comparable type, written a..b or a..=b (§3 Range literals). It is opaque: its parts are reached through std::ranges. It implements Iter<T> when T implements Discrete.
  • (A, B, ...) is a tuple and {name: A, ...} an anonymous struct (below).
  • (A, B) -> C is a function type (§7).

The functions over each type are in the standard library reference: std::lists, std::vectors, std::maps, std::sets, std::ranges and std::iter.

Taught in Structs, Enums & Distinct Types.

A tuple is written (a, b, ...): fixed-size, positional, of mixed types, with at least two items. Its type is written the same way, (Int, String), and so is its pattern. Its items are read by ordinal name, counting from one as captures do: t.first, t.second, t.third, … up to t.twentieth. A tuple type is structural: two tuples of the same item types have the same type.

fn divide(x: Int, y: NonZeroInt) -> (Int, Int)
    (x / y, x % y)
end

fn main()
    (q, r) = divide(10, 3)
    dbg (q, r)              // (3, 1)
    dbg divide(7, 2).second // 1
end

A named tuple, a distinct type over a tuple (§4 Distinct Types Over Tuples and Maps), reads its items the same way: Pair(1, "x").first is 1. Only a tuple has ordinal names; a struct’s field called first is an ordinary field.

Items are never read by number. t.0 is the error tuple items are read by ordinal name, not by number: write `t.first`, whose fix writes the ordinal, and t.1.0 is the same error for t.second.first. An item past the twentieth has no name: t.20 is tuple items are read by ordinal name, `.first` to `.twentieth`, and item 21 has none, and such an item is bound by a pattern ((a, b, ...)). A tuple that wide is better written as a struct. An ordinal past a tuple’s last item is (Int, Int) has 2 items, so it has no `third`; its last is `second`.

A comma at the top level of parentheses makes a tuple. Without one, parentheses only group, in an expression, a pattern and a type: (x) is x, and ((Int)) is Int. (1,) is a tuple has at least two elements; `(x)` is grouping. Use a struct or distinct type if you need a wrapper, and () is `()` is no value: a tuple has at least two elements, and the empty value is `Unit`. A trailing comma is allowed after a tuple’s last item, as in a list.

A tuple passed as a call’s one argument is written in its own parentheses, f((a, b)). In a type, (A, B) -> C is a function of two parameters, and a function that takes one tuple is ((A, B)) -> C: a -> after the ) makes the parentheses a parameter list. () -> C takes no parameters; there is no empty tuple.

A tuple has no #: #(1, 2), as a value, a pattern or a type, is a tuple is written without `#`: `(a, b)`, whose fix drops the #.

Taught in Structs, Enums & Distinct Types.

An anonymous struct is written {...} with named fields and no type name. A field may be punned: {name:} is {name: name}. Its type is its shape, written as the value is ({morning: String, night: String}), and may stand in any type position: a parameter, a field, a type argument, a tuple item, a typealias.

Two anonymous struct types are the same when their fields have the same names and types, in any order. There is no width subtyping: a parameter of type {x: Int} takes exactly that shape, not one with more fields (argument 1: expected {x: Int}, got {x: Int, y: Int}) and not a nominal struct with those fields. A field name shared by two types is not a shared meaning, so code that works across shapes declares an interface, builds an anonymous struct at the call, or converts explicitly.

type Foo {...} is an error whose message says a type over an anonymous struct is a struct, declared with struct Foo, one field per line, and end. An anonymous struct has at least one field: {} as a literal, a type or a pattern is an anonymous struct has at least one field. A struct whose fields all have defaults is built by its name, Settings{}.

List<T> is a linked list, literal [1, 2, 3]. [x, ..xs] puts x in front of xs. A list pattern takes a list apart from the front (§10).

Vector<T> is a random-access sequence, indexed from 0. Its literal is [1, 2, 3] where a vector is expected and Vector[1, 2, 3] anywhere (§3 Literal forms). A bracket pattern takes a vector apart from either end (§10).

Map<K, V> maps keys to values, literal {key => value}. Any value with equality can be a key (§5 Equality and Ordering Semantics). A map iterates in insertion order: putting a new key appends it, and putting an existing key keeps its position. Maps combine with + (§8 Arithmetic operators).

Set<T> is a collection of unique values. Its literal is [1, 2, 3] where a set is expected and Set[1, 2, 3] anywhere (§3 Literal forms). Any value with equality can be an element, unique under ==. A set iterates in first-insertion order, and sets combine with + and - (§8 Arithmetic operators). A set implements Equatable and Hashable, not Comparable. A bracket pattern over a set tests membership and never covers every set (§10).

Taught in Structs, Enums & Distinct Types.

A struct body is a list of fields, one name: Type per line (or separated by ;), with an optional default. Field names are snake_case.

struct User
    name: String
    age:  Int
    role: String = "member"
end

fn main()
    user = User{name: "Ada", age: 36}
    dbg user.role // "member"
end

Two fields on one line with no ; between them, x: Int y: Int, are the error struct fields are newline- or semicolon-separated, and a comma between fields is an error too. The newline rule is for declaration bodies only: an anonymous struct type, a struct literal and a struct-shaped variant (Card {rank: Int}) keep commas.

A field may have a default, which construction uses when it leaves the field out. A field without a default must always be given. A default expression runs once per construction that omits its field.

A default has no function to exit, so a ?, return, break, continue or assertion written directly in it is an error at that token: `?` cannot be used in the default of field 'port' of Config: a default has no function to return from. An exit inside a lambda the default builds belongs to the lambda.

A field with a default may leave out its type: misses = 0 is an Int field. Its type is the default’s, checked with no expected type, so it is known when nothing in the default is left open: a literal, a typed literal with its tag (Route"GET /admin/{$}" is a Route<Unit>), a struct literal or a constructor call, a call (a function’s declared result), a non-empty collection literal, an operator over such values, or a read of a once or of another field whose type is known. An untagged string literal is a String, even where the field is meant to hold a checked literal.

struct Game
    word: String
    misses = 0
    guessed: Set<String> = []
end

fn main()
    game = Game{word: "nomi"}
    dbg game.misses + 1 // 1
end

A default whose type only an expected type tells ([], Set[], {}, Vector[], None, a .Variant, or a generic call nothing fixes the type arguments of) is an error at the field, with help that writes the annotation: can't tell this field's type from `Set[]`, with write `guessed: Set<_> = Set[]`, with the type for each `_` . A default that reads its own field’s type, directly or through other such fields, is can't tell this field's type from `Bad{}.loop`: it depends on a type that comes from this default.

The inferred type is part of the struct’s interface, as a written one is: another file reads it, and a public struct’s field may not take a private type from its default (public struct field exposes private type Secret). derive FromJson decodes each field by its written type, so it refuses a field without one: `derive FromJson for Cfg` needs field 'port' to have a written type.

A struct-shaped variant’s fields take defaults the same way. A positional payload and a bare variant cannot: Circle Float = 3.14 is a positional variant payload can't have a default; name the field to give it one: `Circle {<name>: Float = <value>}`, and North = 1 is enum variant `North` carries no value, so it can't be assigned one.

A field whose value may be absent has type Maybe<T>. That is independent of a default, which only spares the caller from writing a value: nickname: Maybe<String> = None is optional and defaults to absent.

A struct literal names each field: User{name: "Ada", age: 36}. A field whose value is a binding of the same name may be punned: User{name:, age:} is User{name: name, age: age}, and punned and named fields mix. A struct has no positional construction. The name must be a struct’s (or a struct-shaped variant’s, Shape.Rect{...}): Context{} is `Context` is a host type, not a struct, so a struct literal cannot build it, and an enum, a distinct type or an interface is the same error.

A struct literal names each field at most once: User{name: "Al", name: "Bo"} is field 'name' is given twice in this User literal, at the second. The same holds for an anonymous literal (this struct literal), a struct-shaped variant (this Rect literal), the fields after a spread and a Struct.update patch. A field after a spread may repeat a field of the base.

A struct also has a call form: the type name applied to one anonymous struct value whose fields match, with defaulted fields optional. A generic struct infers its type arguments from it.

struct Box<T>
    v:     T
    label: String = "box"
end

fn main()
    b = Box({v: 1})                  // a Box<Int>
    dbg b == Box{v: 1, label: "box"} // True
    dbg {v: 2} |> Box()              // Box{v: 2, label: "box"}
end

{...}, a struct literal with no type name and no spread, builds the nominal struct its position expects, as the dot of .Circle{radius:} stands for Shape: {x: 0} is Point{x: 0} where a Point is expected. The positions that supply a struct are the ones that supply an enum to a .Variant (Variant Resolution):

  • an annotated binding or once;
  • a struct field in construction, and a function or constructor argument;
  • a return value or block tail;
  • an element of a typed List, Set, Vector or Map literal;
  • a case or if arm whose result has an expected type;
  • an operand of ==, !=, <, >, <= or >=, against the other operand’s type;
  • a generic position once its type argument is known (b: Box<Int> = {v: 3}, Some({...}) under Maybe<Address>), the enclosing function’s own type parameters among them (Some((x, {...})) under Maybe<(T, Box<T>)> builds a Box<T>).
struct Address
    street: String
    city:   String
    zip:    String = "00000"
end

struct Person
    name:    String
    address: Address
end

fn home() -> Address
    {street: "1 Main", city: "Bath"}
end

fn main()
    ada = Person{name: "Ada", address: {street: "3 Main", city: "York"}}
    dbg home().zip       // "00000"
    dbg ada.address.city // "York"
end

The literal follows the ordinary construction rules and builds exactly what Address{...} builds. Errors name the struct: missing field 'street' of Address, field 'city' of Address: expected String, got Int, Address has no field 'zip'. An opaque struct is built this way only in its defining file.

Where no struct type is expected, {...} is an anonymous struct. It stays anonymous where the expected type is an anonymous struct type, an interface, a type parameter or an enum, since none names one struct to build. An interface takes the anonymous struct when the struct implements it: a: Display = {street: "x", city: "y"} holds an anonymous struct, which has Display when each field does (§12), and a: Comparable = {street: "x", city: "y"} is type mismatch: expected Comparable, got {street: String, city: String}. An enum takes none: c: Color = {street: "x"} is type mismatch: expected Color, got {street: String}.

Taught in Structs, Enums & Distinct Types.

A struct update builds a new struct from an old one with some fields replaced. It is written as a literal, {..base, field: value}, or as a call, Struct.update(base, {field: value}). The two admit the same fields and the same nested .. literals, and mean the same thing.

struct Point
    x: Int
    y: Int
end

fn main()
    p = Point{x: 1, y: 2}
    dbg {..p, x: 9}              // Point{x: 9, y: 2}
    dbg Struct.update(p, {y: 0}) // Point{x: 1, y: 0}
end

The literal form takes exactly one spread, written first, and at least one field:

  • {..p} is a struct spread with no fields is its base value; write `p`.
  • Two spreads, or a spread after a field, is struct spread `..` must be the first element.
  • A named form, Point{..p, x: 1}, is struct spread `..` has no named form; write `{..base, field: value}` — the spread head carries the type.

The result has the base’s type: a nominal struct gives that struct, an anonymous struct an anonymous struct. The fields are checked as a struct literal’s are, against the base’s field types, except that a missing field is not an error. A punned field works after a spread: {..base, name:}.

Struct.update(original: self, updates: Partial<self>) -> self is the one function of Struct, the interface every struct, named or anonymous, satisfies; Struct is in the prelude. Partial<self> is an anonymous struct whose fields are a subset of the target’s. An unknown field (User has no field 'bogus') and a field of the wrong type (field 'age' of User: expected Int, got String) are errors. A patch held in a binding is checked by its type, and its fields must be whole values. Struct.update takes a patch as a value, which the literal form cannot.

Nested updates. At a field or key of an update, a bare .., with no base written, stands for the value already there. A literal holding one is that value with the changes written. A literal without one is a whole new value that replaces the field.

struct Address
    street: String
    city:   String
end

struct Person
    name:    String
    address: Address
end

fn main()
    ada = Person{name: "Ada", address: Address{street: "1 Main", city: "Bath"}}
    moved = {..ada, address: {.., city: "York"}}
    dbg moved.address // Address{street: "1 Main", city: "York"}
end

{..ada, address: {city: "York"}} is therefore a whole Address with no street, the error missing field 'street' of Address, whose help suggests {.., city: "York"}. A diagnostic names the type the mistake is in: {..ada, address: {.., zip: 1}} is Address has no field 'zip'.

A .. is also an operand anywhere in a field’s or key’s new value, and it is then the value already there, with the field’s type: visits: .. + 1, name: String.trim(..), tags: .. |> Iter.filter(keep) |> Iter.to_list(). It belongs to the innermost field or key whose value holds it, so in address: {.., street: rename(..)} the first .. is address and the one in rename(..) is street. It keeps that meaning inside a lambda written in the value (street: Maybe.map(m, fn s -> s + ..)). The update’s base is evaluated once, however many ..s read it.

struct Address
    street: String
    city:   String
end

struct Account
    owner:   String
    visits:  Int
    address: Address
end

fn main()
    a = Account{owner: " Ada ", visits: 2, address: Address{street: "Main", city: "Bath"}}
    b = {..a, owner: String.trim(..), visits: .. + 1, address: {.., street: .. + " St"}}
    dbg b // Account{owner: "Ada", visits: 3, address: Address{street: "Main St", city: "Bath"}}
end

A .. is an operand when what follows it is not one: ), ,, ], }, a binary operator, |> or a line end. ..e at the start of a literal’s element is still a spread, and a..b still a range; a range needs both bounds and a call takes no spread, so f(..) means only this. A field whose whole value is .. is a field or key whose value is `..` keeps the value it holds; leave it out. A .. operand outside a field’s or key’s value in an update, such as x = .. + 1 or in a named literal Address{street: .., ...}, is `..` means the value already at a field or key of an update, and this `..` is not in one.

The .. is the one way to write the value already there. A nested struct update whose spread names that value as a path, the enclosing update’s base followed by the field it is written at, is `..ada.address` is the value `address` already holds here: write `..`: {..ada, address: {..ada.address, city: "York"}} is an error, and so is {..ada, address: {.., geo: {..ada.address.geo, lat: 1}}}, where the enclosing .. is ada.address. The same holds in the literal patch of Struct.update(ada, {...}). Paths compare by the bindings they name, not their text. A spread naming another value ({..bob.address, city: "York"}) is a value like any other. A base that is not a binding or a chain of field reads of one, such as a call ({..load(), address: {..load().address, ...}}), has no such path, since a .. would not run the call again. An operand that reads the field by its path, street: rename(ada.address.street) in an update of ada.address, means the same as rename(..) and is no error; the editor marks it with a hint that .. writes it.

At a field or key holdingWriteMeans
a struct{.., f: v}the struct with f replaced
a map{.., k => v}Map.merge(old, {k => v})
a list[x, ..] or [.., x][x, ..old] or [..old, x]
a set[.., x]Set.union(old, Set[x])
a vector[.., x] or [x, ..]old with x after, or before

The literal is the collection the field or key holds, as any bracket literal is the one its position expects. A bare .. may stand anywhere a spread may, beside other spreads, and a literal takes one: a second is list literal takes one bare `..` (or map). A literal whose .. is followed by nothing ([..]) is an update with nothing after `..` changes nothing; leave this field or key out.

A bare .., as a spread or an operand, is legal only in the value of a field or key of a literal that is itself an update: one with a named spread ({..base, ...}), one with a bare .., or the literal patch of a Struct.update call. Anywhere else, at the top of a plain literal, in a list element, in an operand of + or Map.merge, in a call argument (Some({.., ...}) included) or in a patch passed to another function, it is a bare `..` has no value to update here.

A .. must stand for a value of its literal’s kind: {.., f: v} at a list field is struct spread `..` requires a struct, got List<Int>. A Maybe field has no .. form, since it may hold no value; it takes a whole value: {..p, a: {.., city: "x"}} with a: Maybe<A> is struct spread `..` requires a struct, got Maybe<A>. A field of interface type takes values only: {..stage, who: {.., n: 2}} is struct spread `..` requires a struct, got Speaker. A field whose type is a type parameter takes a .. literal once the argument is known.

In a map update the base may lack an entry’s key. A .. there stands for nothing, and the literal builds the value: an empty collection with the entries written, or a struct from the fields written and its defaults. Positions inside a missing value are missing too. A struct whose left-out field has no default is a compile error, never a trap: a missing key leaves `..` no Geo to update, and field 'city' has no default. A .. operand there is the empty collection when the value is one ({..lists, "a" => .. + [1]}), and otherwise an error, since there is no value to read: {..counts, "a" => .. + 1} is a missing key leaves `..` no Int to read, whose help suggests Map.update(m, key, default, f).

fn main()
    team = {"home" => {"city" => "Atlanta"}}
    moved = {..team, "home" => {.., "arena" => "State Farm"}, "away" => {.., "city" => "Leeds"}}
    dbg moved // {"home" => {"city" => "Atlanta", "arena" => "State Farm"}, "away" => {"city" => "Leeds"}}
end

m + {k => v} and Map.merge stay shallow: a bare .. in their operands has no value to update.

Every struct satisfies Struct by its shape, and no other type does. Requiring Struct of another type, as Struct.update(5, ...) or a where T: Struct bound does, is a compile error (Int does not implement Struct). Struct works as a bound and as an interface value. It cannot be implemented: impl Struct for P is `Struct` is a built-in structural marker and cannot be implemented; every struct satisfies it automatically — remove this `impl Struct for P`.

An opaque struct satisfies Struct too. What opacity closes is a patch that names one of its fields outside its defining file: cannot update field 'value' of opaque type 'Counter' outside its defining module, through any depth of nesting. Replacing an opaque field whole names none of its fields and is legal.

Taught in Structs, Enums & Distinct Types.

An enum body lists its variants, one per line. There is no | and no single-line form. Variant names are PascalCase and unique within the enum.

struct Circle
    radius: Float
end

enum Shape
    embeds Circle
    Rectangle {width: Float, height: Float}
    Segment (Int, Int)
    Point
end

A variant is one of four kinds:

  • A bare variant, a name alone: Point, None.
  • A single-payload variant: a name and one type expression, with no parentheses, as a distinct type’s declaration writes it: Some T, Milliseconds Int, Segment (Int, Int), Computation (Int) -> Int. Several values go in a tuple, a struct or a struct variant; Rectangle Float, Float is a parse error.
  • A struct variant: a name and named fields in braces, with optional defaults: HttpError {status: Int, retryable: Bool = False}.
  • An embedded type: embeds Name, a struct or distinct type declared on its own (Embedded Types).

A variant constructor makes a value of the enum type. There is no separate variant type: Some(42) is a Maybe<Int>, and Animal.Dog("Rex") an Animal with no annotation.

A variant is written qualified, Shape.Circle(5.0), or dot-leading, .Circle(5.0), where the expected type is its enum (Variant Resolution). A bare variant name is an error even in its own file: variant 'Red' must be qualified through its enum; use 'Color.Red'. The prelude’s Some, None, Ok, Err, True and False are bare names through ordinary name resolution; .Ok(x) resolves too. A user enum cannot join the prelude, but an owner selector import lifts chosen variants into bare scope (import shape.Shape.{Circle, Point}, §14).

Each kind builds as its shape does:

enum Shape
    Circle Float
    Rectangle {width: Float = 2.0, height: Float}
    Point
end

fn main()
    a = Shape.Circle(1.0)
    b = Shape.Rectangle{height: 3.0}
    c = Shape.Rectangle({width: 1.0, height: 1.0})
    d: Shape = .Point
    dbg [a, b, c, d] // [Circle(1.0), Rectangle{width: 2.0, height: 3.0}, Rectangle{width: 1.0, height: 1.0}, Point]
end

A single-payload variant over a tuple also has a flat call: Shape.Segment(1, 2) builds from the elements, a pipe’s head is the first (2 |> Shape.Segment(3)), and a generic variant’s type arguments are solved from them. A struct variant has no positional form: Shape.Rectangle(4.0, 5.0) is Shape.Rectangle is a struct-shaped variant and has no positional form; construct it with Shape.Rectangle{...} or Shape.Rectangle({...}). A struct variant’s paren pattern matches the anonymous struct of its fields, so .Rectangle(r) binds that record.

A list-, map-, vector- or set-payload variant written as a literal (Bag.Items[1, 2], Named{"a" => 4}) infers a generic enum’s type arguments from its elements, as an empty one takes them from the expected type. A variant lifted into bare scope by an owner selector infers them as the qualified spelling does: after import shapes.Holder.{Items, Of}, Of{value: 1} and Items[1, 2] are each a Holder<Int>.

A variant’s name never takes the place of another name in its file. Since a same-file variant is never referenced bare, a variant may share its name with a type, interface or function the file declares or imports, and the bare spelling means that other name. The variant stays reachable as Enum.Variant, .Variant and in patterns.

Taught in Structs, Enums & Distinct Types.

A .Variant expression, in any spelling (.V, .V(x), .V{...} for a struct-shaped variant or a map payload, .V[...] for a list, vector or set payload), resolves to variant V of enum E when the expected type at its position is E. The expected type is the one the checker’s outside-in walk finds, from the position up to the enclosing declaration. The walk passes through:

  • case and if arm results, block tails and return values;
  • bracket, tuple and map literal elements, including the heads before a spread;
  • an argument of a generic function or constructor whose type parameter the call’s return type pins against an outer expected type, the head of a pipe into such a call included. The constraint is solved before the argument holding the variant is checked, for the type parameters the arguments before it left open (§5 Type arguments from the arguments), so it reaches a variant nested anywhere in it, and through an if or case argument’s branches;
  • an operand of ==, !=, <, >, <= or >=, which is checked against the other operand’s type (k == .Deposit, .Deposit == k);
  • a lambda’s result, checked against the callback’s declared result (Iter.sort_with(xs, fn a, b -> .Equal)), unless that result holds a type parameter;
  • a pattern, whose expected type is the scrutinee’s (§10).

A bracket literal checked against Iter<T> checks each item against T. The expected type may name the enclosing function’s own type parameters: in fn write<T>(b: Buffer<T>, item: T) -> Result<Buffer<T>, Error>, Err(.Full) takes E as Error, and in fn pop<T>(...) -> Maybe<(T, Stack<T>)>, Some((x, {items: []})) takes its payload as (T, Stack<T>), so the literal builds a Stack<T>. A callee parameter is not pinned to a type that names the callee’s own parameters, as a recursive call’s expected type would.

The walk does not look at later uses, at unannotated bindings, or at a bare .Variant written as a pipe stage, which would need the type of the stage after it. A comparison’s own expected type is never its operands’.

With no expected type, a bracket or map literal checks its elements left to right, and each element after the first is checked against the type the earlier ones give, when that type holds an enum, a named struct, or a vector, a set or a distinct type over a collection that an unnamed literal in the element takes (§3 Literal forms). A map’s keys and values are two positions. So [Color.Red, .Green] is a List<Color>, {Nucleotide.A => 0, .C => 0} a Map<Nucleotide, Int>, [Point{x: 0, y: 0}, {x: 1, y: 2}] a List<Point>, and [Set[1], [2]] a List<Set<Int>>. The earlier element’s whole type is what a later one is checked against, so the rule reaches into nested literals: [Some(Color.Red), Some(.Green)] resolves. An element whose type is still open sets nothing and blocks nothing. A tuple’s items are separate positions, so (Color.Red, .Green) gives .Green nothing.

A case or if with no expected type does the same for its arms: each arm after the first is checked against the type the earlier arms give. A diverging arm (todo, return) gives nothing.

SiteResolves?
Box{color: .Red}, paint(.Red)yes: the field or parameter type
Iter.sort(xs, .Descending)yes: the parameter type; the file need not import it
palette: List<Color> = [.Red, .Green]yes: the annotation
palette = [Color.Red, .Green]yes: the earlier element
c: Color = id(.Red) with generic idyes: the annotation pins T
exits: Map<Direction, Place> = [(.North, .Cave)] |> Iter.to_map()yes: the pipe’s head is checked against the pinned parameter
Ok(.Quit) in a function returning Result<Input, String>yes: Ok’s payload is pinned from the return
c == .Red, size < .Largeyes: the other operand
c = .Redno: no expected type
palette = [.Red, Color.Green]no: nothing before .Red names the enum
c = id(.Red); paint(c)no: that would need a later use
... |> .Guess() |> Ok()no: a bare pipe stage
.Red == .Blueno: neither operand names the enum

The errors:

  • No enum at the position: .Red requires a determinable enum type at this position; annotate the binding or qualify the variant. In a literal with no expected type, the help asks to qualify the first element, and only the first refused variant is reported. An argument whose parameter type is an unsolved type parameter determines nothing: in String.to_int(s) |> Maybe.to_result(.SyntaxError)? the message is .SyntaxError cannot be resolved here: nothing at this position determines its enum, with help naming E.SyntaxError when one enum in scope declares it.
  • The expected type is not an enum: .Red resolves only to enum variants, but the expected type at this position is Box.
  • The enum has no such variant: no variant 'Purple' on enum Color.
  • Both operands of a comparison are dot-leading: neither operand of `==` names its enum; qualify one variant with the enum's name (write `E.Red` for `.Red`).

Taught in Structs, Enums & Distinct Types.

embeds T makes a struct or distinct type T, declared on its own, a variant of the enum. One type may be embedded in several enums, and it stays a type of its own whether or not an enum embeds it.

Only a struct or a distinct type embeds. An interface is embeds requires a struct or distinct type, got interface Display; for an interface-typed payload use a single-payload variant: `Name Display` and an enum, directly or through a typealias, is `Shape` is an enum, and an enum cannot be embedded in another enum; carry an enum in a single-payload variant (Shape Shape). A distinct type over an enum embeds.

Subtype coercion. An embedded type is a subtype of its enum. A value of the embedded type is accepted wherever the enum is expected: an argument, an annotated binding, a field, a return, a collection element, and a tuple item, record field or type argument of any of those that converts by its variance (§5 Covariant conversion): List<Circle> where List<Shape> is expected, Maybe<Circle> where Maybe<Shape> is. An invariant type argument takes no embedded type: a Cell<Circle> whose fields both hold and take a T is no Cell<Shape>. A construction in such a position builds the expected type. A type parameter an argument solved to an embedded type widens to the enum when a later argument is a value of the enum (pick(c, circle, shape) is a Shape), only where every earlier argument still converts to it: with fn apply<T>(f: (T) -> Int, x: T) and area a (Circle) -> Int, apply(area, shape) is argument 2: expected Circle, got Shape, since area would be called with a shape that may be no circle. A later collection literal widens it too: List.concat([circle], [shape]) is a List<Shape>.

struct Circle
    radius: Float
end

enum Shape
    embeds Circle
    Point
end

fn area(c: Circle) -> Float
    3.0 * c.radius * c.radius
end

fn total(s: Shape) -> Float
    case s
        .Circle{} -> area(s) // s is a Circle in this arm
        _         -> 0.0
    end
end

fn main()
    c = Circle{radius: 1.0}
    shapes: List<Shape> = [c, Shape.Point]
    dbg Iter.map(shapes, total) |> Iter.to_list() // [3.0, 0.0]
end

The enum is never accepted where an embedded type is expected, at any of those positions, since an enum value may be another variant: area(s) with s: Shape is argument 1: expected Circle, got Shape. Matching the value is the way from the enum to the embedded type (§10).

Where the two meet with no direction (the branches of an if or case, the elements of an unannotated literal, two arguments of one type parameter), the result is the enum, inside tuples, records and collections too. When neither side takes the other’s values, as (circle, shape) beside (shape, circle), they do not join and the literal is an error. == compares a Circle with a Shape as two Shapes, at any depth: with s: Shape = c, Some(c) == Some(s) and [c, c] == [s, s] compare two Maybe<Shape> and two List<Shape> values and are True, and Some(c) == Some(Shape.Point) is False.

An impl function may not take the embedded type where its interface’s parameter is the enum, nor return the enum where the interface returns the embedded type. A function value passed as an argument follows the same rule, since the callee calls it: Iter.map(shapes, area) with area(c: Circle) is an error, and Iter.map(circles, total) with total(s: Shape) is accepted.

Construction through a variant. Enum.V followed by a construction takes the forms V’s own shape takes and widens the result into the enum:

  • A struct, inline or embedded: Shape.Circle{radius: 2.0} and Shape.Circle({radius: 2.0}), prefix or piped, with defaults filling omitted fields.
  • An embedded distinct that wraps a value: the distinct’s call form, Session.UserId("alice"), from the wrapped value.
  • An embedded zero-sized type: the value alone, Session.Expired. Session.Expired() is Session.Expired is a zero-sized variant and takes no arguments; write Session.Expired.

A value that is already a V is not built again: Shape.Circle(c) with c: Circle is an error whose message says it widens on its own wherever a Shape is expected.

The built value is the same value as V widened: Session.UserId("alice") equals UserId("alice") widened into Session, renders the same and matches Session.UserId(name) with name bound to "alice".

Dispatch follows the static type. A value typed as the enum runs the enum’s impls, however it became one; the same value typed as the embedded type runs the embedded type’s. An enum’s automatic Debug and its derived impls hand an embedded variant to the embedded type’s impl.

Payload shape. Matching an embedded variant binds:

  • for an embedded struct, the struct (Shape.Circle{radius:} destructures its fields);
  • for an embedded distinct that wraps a value, the wrapped value (Identifier.UserId(name) binds the String);
  • for an embedded zero-sized type, nothing.

A field read off the enum. s.radius on a value typed as the enum reads the field from whichever struct-shaped or embedded struct variant the value is. A value of a variant without the field traps: line 8: variant 'Circle' has no field 'w'. Every variant that has the field must give it one type, or the read is field 'w' is Int in Shape.Rect and Float in Shape.Circle, so reading it off a Shape has no one type.

An embedded type is a type of its own, so a function that handles one variant takes it as a parameter (fn area(c: Circle) above).

A variant declared inside the enum is not a type, bare or qualified: fn perimeter(rect: Shape.Rectangle) is unknown type "Shape.Rectangle", with the help `Rectangle` is a variant of `Shape`, not a type: take a `Shape`, or declare `Rectangle` on its own and write `embeds Rectangle` in `Shape`. A function that takes one variant takes an embedded type, and a case arm that matches that variant narrows an enum value to it (§10 Type Narrowing). An embedded variant’s qualified name is not a type either: Shape.Circle is unknown type "Shape.Circle", with the help write `Circle`, the embedded variant's own type.

Taught in Structs, Enums & Distinct Types.

A type declaration makes a new nominal type, distinct from every other type, its representation included. What follows the name decides its kind:

  • a tuple type (type Pair (Int, String)), at least two items;
  • a generic type (type Kvs Map<String, Int>, type Ids List<Int>);
  • a single type name (type Id Int, type Origin Point, type Twice Meters);
  • a function type (type Handler (Request) -> Response);
  • nothing: a zero-sized type (type Expired).

A type declaration may add a when rule, which makes it a validated type (Validated types below), and a type over a subtype is built the same checked way. A subtype declaration is no new identity: its values are values of the types it names (Subtypes below). The rest of this section is about distinct types without a rule.

A type declaration has no body. type Wrap (Int) is type Wrap Int, since parentheses only group. No = comes between the name and the inner type: type Id = Int is a type has no `=`: write `type X T` .

A distinct type may take type parameters after its name, which its inner type names: type Tagged<T> (String, T), type Ids<T> List<T>. Its call form solves them from the value it wraps, as a generic struct’s literal does: Tagged(("n", 1)) is a Tagged<Int>. A zero-sized type takes none: type Marker<T> is zero-sized `type Marker` takes no type parameters: it has no value for them to describe.

The wrapped type is the representation, so it cannot contain the type itself, directly or through other distinct types: type L List<L> is type 'L' is defined in terms of itself. A recursive type is a struct or an enum, and a distinct type may wrap one.

Every distinct type that wraps a value satisfies the prelude interface Distinct<T> for exactly the type it wraps: type Twice Meters is a Distinct<Meters>, not a Distinct<Int>. A zero-sized type is none. Distinct<T> declares no functions; it is a bound, and on an interface default it lets the body take self apart and build one (§12). impl Distinct<Int> for X is `Distinct` is a built-in marker and cannot be implemented; every distinct type satisfies `Distinct<T>` for the type it wraps — remove this `impl Distinct for X`.

type Id Int

fn raw(Id(n)) -> Int
    n
end

fn main()
    id = Id(42)
    dbg raw(id)   // 42
    dbg 7 |> Id() // Id(7)
    dbg Iter.map([1, 2], Id) |> Iter.to_list() // [Id(1), Id(2)]
end

The call form takes the one value the type wraps, prefix or piped, checked against the wrapped type: Id("42") is Id wraps Int, so Id(...) takes an Int; got String. A distinct over a tuple takes its tuple, Pair((1, "x")), or the tuple’s elements, Pair(1, "x"). Any other number of arguments is Pair wraps (Int, String), a tuple of 2 elements; got 3, and 1 |> Pair("x") is Pair takes the piped value as its only argument, got 1 more.

A distinct’s value is read by destructuring, in any pattern: a binding (Id(n) = id), a case arm, an if pattern, a binding with else, a parameter (fn raw(Id(n))). Destructuring reads one level: for type A Int and type B A, B(a) = b binds an A.

A zero-sized type is its own one value, written bare: Expired. It has no call form: Expired() is Expired is a zero-sized type and takes no arguments; write Expired. It may implement interfaces and be embedded, as a standalone bare variant.

A distinct type implements interfaces as structs and enums do. A distinct type that wraps a value, named without a call, is its constructor as a function value (§7 Constructors as Function Values).

A type name is not a conversion, a function or a value:

  • Int(id), Int("4") and String(4) are `Int` is a type, not a function. On a distinct argument the help names the destructuring to write; otherwise it names the conversion (String.to_int, Int.to_float, "${x}").
  • Calling any other type name is that error too (Dir(1), Maybe(3)). The type names with a call form are a struct and a distinct type. A pipe into a type name is the same call: 1 |> Point() is Point expects an anonymous struct literal {...} matching its fields, got Int.
  • A type name standing as a value, f = Int or Iter.map(xs, String), is `Int` is a type, not a value. The names that are values are a variant, a distinct constructor, a zero-sized type, True, False, Unit, and a type name where a Type<T> witness is expected (Context.value(c, TraceId)).
  • An opaque struct or distinct type has no call form outside its defining file.

A distinct type whose underlying type has a shape literal (tuple, list, vector, set, map) has two construction forms: the named literal, from the elements, and the call form, from a value of the underlying type. A struct has the same two. A tuple’s named literal is a call with the tuple’s elements as its arguments, so it has no symbol, as a struct’s literal has none.

DeclarationNamed literalCall form
type Id IntnoneId(42)
type Pair (Int, String)Pair(1, "x")Pair((1, "x"))
type Ids List<Int>Ids[1, 2]Ids(xs)
type Path Vector<Int>Path[1, 2]Path(v)
type Tags Set<String>Tags["a", "b"]Tags(s)
type Kvs Map<String, Int>Kvs{"a" => 1}Kvs(m)
struct UserUser{name: "Ada"}User({name: "Ada"})
type ExpiredExpiredExpired

Where a distinct type over a list, vector, set or map is expected, the unnamed literal builds it as the named one does: p: Path = [1, 2] and k: Kvs = {"a" => 1} (§3 Literal forms). Kvs{} is the empty Kvs.

The named literal checks each element: Pair("x", 1) is element 1 of Pair: expected Int, got String, and Pair(1) is Pair wraps (Int, String), got Int. Patterns mirror construction (§10). A named tuple reads its items by ordinal name, as its tuple does: Pair(1, "x").second is "x", and Iter.map(pairs, .first) reads each pair’s first item.

Taught in Modules & Imports.

opaque before struct, enum or type keeps a type’s representation private to its defining file. It is written with pub, which makes the name visible to other files; opaque type T Int without pub is accepted, and changes nothing, since the type is private to its file anyway. Outside the defining file the type may be named in signatures, fields and type arguments, passed around, compared with == and given to interface functions. These are rejected:

Outside the defining file
PositiveInt(5), Date{...}, Status.Active (construction)rejected
PositiveInt(n) = p, a case on its variants (destructuring)rejected
d.year, a named tuple’s p.first (field and item access)rejected
Struct.update(d, {year: 1}), {..d, year: 1} (a patch naming a field)rejected

Inside the defining file every form works. An opaque enum’s variants are unreachable outside it for construction, matching and payload access alike.

// positive.nomi
pub opaque type PositiveInt Int

pub fn positive(n: Int) -> Maybe<PositiveInt>
    if n > 0 then Some(PositiveInt(n)) else None
end

pub fn to_int(PositiveInt(n)) -> Int
    n
end

Opacity restricts these operations and nothing else. An opaque type satisfies every interface a transparent one would, at bounds and as an interface value: Struct, Distinct<T>, Debug, Display, Equatable. Its automatic Debug renders <opaque T>, inside and outside its file. An interface default that takes self apart or builds one does not apply to an opaque type implemented outside its file; that impl writes the function (§12).

opaque applies to a struct, an enum and a distinct type with a representation. On a function, a type alias, an interface, a once, a zero-sized type, a foreign type or a built-in type it is an error at the declaration. An opaque type’s representation may be private, since no caller outside can reach it (§14).

Taught in Structs, Enums & Distinct Types.

A subtype declaration names a narrower set of another type’s values: its name, the types it narrows, its parents, joined by and, and a rule, when and a function from its first parent to Bool, a lambda or a function’s name. A struct may declare a rule too, as its body’s last item, on its own line after every field; a rule over several lines keeps its own end inside the struct’s. Such a struct is a validated struct.

subtype NonNegative Float when fn x -> x >= 0.0

subtype Positive NonNegative when fn x -> x > 0.0

subtype Port Int when fn port -> port >= 1 and port <= 65535

fn is_tag(s: String) -> Bool
    String.length(s) > 0 and not String.contains(s, " ")
end

subtype Tag String when is_tag

struct Span
    low:  Int
    high: Int
    when fn span -> span.low <= span.high
end

fn half(x: Float) -> Float
    x / 2.0
end

fn main()
    p: Positive = 2.5
    dbg half(p)                          // 1.25
    dbg Positive.try_from(-1.0)          // None
    dbg Port(8080) + 1                   // 8081
    dbg Tag.try_from("two words")        // None
    dbg Span.try_from({low: 3, high: 1}) // None
end

The rule is checked as a (P) -> Bool, where P is the subtype’s first parent: fn x -> x + 1 is type mismatch: expected (Float) -> Bool, got (Float) -> Float. A validated struct’s rule takes the struct. A when after the struct’s end, on its line, is a struct's `when` rule goes inside its body, after its fields, and one above a field is a struct's `when` rule comes after every field. The rule is a pure function of its value: it may call pure functions and read a once with no effects, and a rule that reaches an effect (§19 Effects) is an error at the declaration, the rule of Noisy has effects (loud calls io.print): a rule is a pure function of the value it checks. A subtype is declared at the top of a file. It cannot be opaque, since its point is that its base is visible: a subtype cannot be opaque: `Secret`'s values are values of its parent, which every file sees; drop `opaque`, or declare a new type, `opaque type Secret ...`, and check values in its constructor.

A subtype narrows. Its when is optional only where its parents narrow already: a subtype of two or more parents with a rule among them is their intersection, subtype PositiveInt NonNegativeInt and NonZeroInt, and needs no rule of its own. A subtype with no rule anywhere in its chain is an error that names the alias it amounts to, a subtype with no rule has the same values as Float: `Celsius` adds no `when`, and nothing it narrows has one with the help name it with `typealias Celsius Float`, declare a new type with `type Celsius Float`, or give the subtype a rule with `when` , and so is one of a single parent with no when of its own, whose rule is all in the parent: subtype Small Digit is a subtype of one parent with no rule of its own has the same values as Digit: `Small` adds no `when` , with the help naming typealias Small Digit. A where bounds the type arguments, not the values, so subtype Sortable<T> NonEmptyList<T> where T: Comparable with no when is that error too, whose help names typealias Sortable<T> NonEmptyList<T> where T: Comparable.

A subtype’s parent may itself be a subtype, as Positive narrows NonNegative, and a subtype may have several parents joined by and: with subtype NonZero Int when fn n -> n != 0 and subtype Count Int when fn n -> n >= 0, `subtype Size Count and NonZero when fn n -> n

0is aCountand aNonZero. Its parents, their parents and so on are its *ancestors*. Following parents from a subtype reaches its *base*, the first type that is no subtype (FloatforPositive), and every parent of a subtype reaches the same base, since the subtype's value is that one value at run time: ``the parents of Mixed narrow different types: Count is an Int and Tag is a String``. A parent named twice, and a parent that reaches the subtype itself (subtype A B and C when …withsubtype C A when …), are errors at the declaration. A value of a subtype is a value of each of its ancestors: it converts to each of them and to its base wherever one is expected, implicitly, at the top and at every position a value converts at ([§5 *Covariant conversion*](/spec/type-relations/#covariant-conversion)), so a Listis aListand aListis aList. Nothing converts down or across: a NonNegativeis noPositive, a Countis noNonZero, and of two subtypes of one parent, subtype Even Int when …andsubtype Odd Int when …, neither converts to the other. The one conversion down is into a subtype with no rule of its own: its values are exactly the values of all its parents, so a value of every parent converts into it. With subtype Strict NonNegativeInt and NonZeroInt, a PositiveIntpasses where aStrictis expected, and aNonNegativeInt` does not.

Where values meet with no type written for them (the branches of an if or case, the elements of a list, vector or set literal and a map literal’s keys and values, a lambda’s results, two arguments of one type parameter, a range’s endpoints), a subtype and an ancestor of it, or two subtypes that share one, join as the nearest ancestor they share, which is the base when nothing nearer is. if c then List.length(xs) else -1 is an Int; PositiveInt beside NonZeroInt is a NonZeroInt, and NonNegativeInt beside NonZeroInt is an Int. They join the same way at every position a value converts at: [Some(List.length(xs)), Some(-1)] is a List<Maybe<Int>>. A literal beside values of a subtype there, in any order, is the nearest of that subtype and its ancestors that is a std numeric subtype (Value ranges) whose rules the literal satisfies, which the compiler decides as it checks the program, and the values join as that type: with n a NonNegativeInt, if c then n else 0, if c then 0 else n, [0, n] and Maybe.with_default(Iter.find_index(xs, f), 0) are NonNegativeInts, and with s a subtype Small NonNegativeInt when fn n -> n < 10, if c then s else 1 is a NonNegativeInt. A literal that satisfies none is its base’s, so Maybe.with_default(Iter.find_index(xs, f), -1) is an Int, and so is a literal beside a subtype whose rule only the built program runs: with p a Port, if c then p else 80 is an Int. A range with no type written ranges over its endpoints’ base: 0..List.length(xs) is a Range<Int>. A type written for the value still decides it, so m: NonNegativeInt = if c then 1 else 2 checks each literal against the rule. A type parameter solved to a subtype widens to the ancestor only where every argument it was solved from converts to it: with fn apply<T>(f: (T) -> Int, x: T), count a (NonNegativeInt) -> Int and i an Int, apply(count, i) is argument 2: expected NonNegativeInt, got Int. A later argument that is a collection literal widens it the same way: with n a NonNegativeInt, List.concat([n], [i]) is a List<Int>.

A subtype’s value is its base’s at run time: converting up costs nothing, and Debug and Display show the base value (dbg p prints 2.5). It has its base’s impls, so a subtype of a List, Map, Vector, Set or String is iterated, spread, matched and tested with in as its base is (Iter.sum(p) with p: Pair), and implements no interface of its own: impl Display for Port is a subtype implements no interface of its own: `Port` is an Int at run time and has Int's impls, and so is a derive. Functions in an inherent block, impl Port, are allowed. An interface impl whose interface takes a subtype as an argument (impl Add<Port, Int> for Int) is an error, since the impl at the base serves the subtype already. The right operand of /, %, <<< and >>> is the exception: an impl of Divide, Remainder, ShiftLeft or ShiftRight may take a subtype there, which states the operands the operator takes, as std’s impl Divide<NonZeroInt, Int> for Int does (§8 Integer division and remainder). An operand of a subtype is its base’s value: p + 1.0 is a Float, port == 80 compares Ints, and a literal pattern matches a narrowed value. The std numeric subtypes are the one exception: an operation on them is the subtype its value’s range proves (Value ranges). An enum cannot embed a subtype. A validated struct is a struct: it converts to nothing, and its rule only constrains how values are built.

A and B of subtypes of one base is a type wherever a type is written: a parameter, a field, a result, a collection’s element, a type’s inner type, a typealias’s target. It is the subtype whose parents are its members and which adds no rule, so a value converts into it when it converts to every member, and it converts to each member and to the base. A literal there is checked against every member’s rule, and the error names the member whose rule fails: half(0) below is 0 is not a NonZeroInt, as NonNegativeInt and NonZeroInt requires: `fn n -> n != 0` is false.

fn half(n: NonNegativeInt and NonZeroInt) -> Int
    n / 2
end

fn main()
    p: PositiveInt = 8
    dbg half(p) // 4
    dbg half(6) // 3
end

The order of the members does not matter, and a member that is an ancestor of another adds nothing: NonNegativeInt and NonZeroInt and NonZeroInt and NonNegativeInt are one type, and PositiveInt and NonZeroInt is PositiveInt. Members of different bases are an error, `and` intersects subtypes of one type, and NonEmptyString is a String where NonNegativeInt is an Int, and so is a member that is neither an interface nor a subtype, `and` joins interfaces or subtypes, and Int is neither. An interface beside subtypes is one their base must implement: NonNegativeInt and Display is a NonNegativeInt, and with interface Named that Int lacks, NonNegativeInt and Named is no value is both NonNegativeInt and Named: NonNegativeInt is an Int, and Int does not implement Named. Intersections join as subtypes do: two of them meet at the nearest ancestor they share.

A subtype may take type parameters, which its parents name: subtype NonEmpty<T> List<T> when fn xs -> not Iter.is_empty(xs). A rule that needs an operation on the elements bounds a parameter with where, written after the parents and before when, as a generic function’s where follows its signature. Parents may carry type arguments, and a subtype may fix its parent’s (subtype IntPair List<Int> when ...).

subtype NonEmpty<T> List<T> when fn xs -> not Iter.is_empty(xs)

subtype Ascending<T> List<T> where T: Comparable when fn xs ->
    Iter.zip(xs, Iter.drop(xs, 1)) |> Iter.all_match(fn (a, b) -> a <= b)
end

subtype Run<T> NonEmpty<T> and Ascending<T> where T: Comparable when fn _ -> True

fn longest(xs: NonEmpty<String>) -> String
    Iter.max_by(xs, String.length)!
end

fn main()
    r: Run<Int> = [1, 4, 9]
    dbg Ascending.try_from([3, 1]) // None
    dbg longest(["ab", "abc"])     // "abc"
    a: Ascending<Int> = r
    dbg a // [1, 4, 9]
end

The rule is checked per instance. A literal of Run<Int> is checked when the program is compiled with T as Int, and T.try_from(x) is generic, its argument solving the type parameters: Ascending.try_from(circles), with Circle no Comparable, is the error Circle does not implement Comparable (required by `where T: Comparable`). A literal of a generic subtype is checked through the try_from of the subtype’s declaration at the literal’s type arguments, whatever the literal’s file names: first([1, 2]) checks its argument against a NonEmpty<Int> parameter of a module whose NonEmpty the file does not import, and an import of NonEmpty used by nothing else is unused. A type argument that breaks a bound is the error at the literal: u: Ascending<Circle> = [] is Circle does not implement Comparable (required by `where T: Comparable`).

A generic rule is checked for effects at its declaration, whatever its type arguments will be: its own body, and through its bounds every impl of their interfaces the program and std have, since any implementor can be the argument. With impl Display for Loud printing, subtype Shown<T> List<T> where T: Display when fn xs -> Iter.all_match(xs, fn x -> Display.to_string(x) != "") is the error the rule of Shown has effects (Loud.to_string calls io.print): a rule is a pure function of the value it checks at its when, with or without a Shown<Loud> anywhere.

A generic subtype’s type arguments convert as its parents’ do (§5 Covariant conversion): a parameter its parents only hold is covariant, so a NonEmpty<Circle> passes where a NonEmpty<Shape> or a List<Shape> is expected when Circle implements Shape, and a NonEmpty<PositiveInt> is a NonEmpty<Int>; a parameter a parent holds as a function’s parameter converts the other way, and one held both ways compares exactly. A join is at the nearest shared ancestor with its type arguments joined: Run<Int> beside Ascending<Int> is an Ascending<Int>. A validated struct takes no type parameters: a validated struct takes no type parameters: `Span`'s rule is checked on values of one struct; a generic subtype narrows a type, `subtype Span<T> ... when ...` .

A value enters a subtype three ways:

  • A literal of the base (a number, a negated number, a string with no ${...}, True or False, or a typed literal with no ${...} such as Duration"15m") where a subtype is expected (an annotation, a parameter, a field, a result, a collection element, an argument of a generic call such as Some(22) as a Maybe<Port>), or as the argument of its call form, Port(8080), is that subtype. A struct literal of a validated struct that writes every field as a literal is one too, and so is a list, vector, set or map literal where a subtype of a collection is expected whose every element, key and value is a literal, through nested collection and tuple literals: with subtype Pair List<Int> when fn xs -> List.length(xs) == 2, p: Pair = [1, 2] and Pair([1, 2]) are checked, and [1, 2, 3] there is this Pair literal breaks its rule: `fn xs -> List.length(xs) == 2` is false. A list, vector, set or map literal where NonEmptyList, NonEmptyVector, NonEmptySet or NonEmptyMap is expected needs no literal elements when its shape proves it holds something: it writes an element or an entry, or spreads a value of one of those types (or a subtype of one). [a, b], Vector[f(x)], Set[x], {k => v}, [..xs, y] and [..ys] with ys a NonEmptyList are each one, with each element checked against the element type as usual. A literal made only of spreads of collections that may be empty, [..xs] with xs a List, is the error `[..xs]` may be empty, and a NonEmptyList holds something: none of its spreads is of a non-empty type, and it writes no element, and an empty one, [], breaks the rule. A subtype declared over one of them keeps its own rule, so its literal’s elements are literals. A literal headed by a collection’s name, List[...], Vector[...], Set[...] or Map{...}, builds a subtype of that collection where one is expected, as the unnamed literal does. A range literal whose endpoints are both literals is one where a subtype of Range is expected: with subtype Wide Range<Int> when fn r -> Range.contains(r, 0) and Range.contains(r, 5), w: Wide = 0..10 is checked, and 0..n there is an error naming n and Wide.try_from. The compiler evaluates the rule of each ancestor that has one on the literal before the program runs, each once, a parent’s ancestors before the parent and the parents in the order they are written, then the subtype’s own; the first that answers False is an error at the literal that names the path to it: -1.0 is not a Positive: Positive is a subtype of NonNegative, and NonNegative's rule `fn x -> x >= 0.0` is false, 0 is not a Size: Size is a subtype of NonZero, and NonZero's rule `fn n -> n != 0` is false, or 0 is not a Port: `fn port -> port >= 1 and port <= 65535` is false. A rule that traps there is the error 0 is not a Trapping: Trapping's rule `fn n -> 10 / n > 1` failed: ... with the trap’s message, and one that does not finish within the compiler’s step limit is an error naming the rule.
  • T.try_from(x), as public as the type, is Some(x) as a T when x satisfies the rule of every ancestor and T’s own, checked through each parent’s try_from in the order the parents are written, and None when it does not. A rule two parents reach through their own parents runs once for each; a rule is pure, so that changes nothing but time. A rule that traps on x counts as false: with subtype Ratio Int when fn n -> 10 / n > 1, Ratio.try_from(0) is None, and the program goes on. It takes a value of the base, or for a validated struct the record of its fields: Span.try_from({low: 1, high: 2}). A subtype implements no interface, so its try_from is its own function, not TryFrom’s.
  • T.unchecked(x) builds a T without evaluating any rule. Only the file that declares T may call it, for functions that keep the rule (adding two non-negative values gives a non-negative one); elsewhere it is `Port.unchecked` builds a Port without checking its rule, and only the file that declares Port may call it.

Any other value of the base where a subtype is expected, unless a check narrowed it (Narrowing) or its range proves the rule (Value ranges), is an error that names try_from: with n: Int, p: Port = n is type mismatch: expected Port, got Int with the help Port is a subtype of Int; check the value with `Port.try_from(...)`, which is `Some` when it satisfies `fn port -> port >= 1 and port <= 65535` and `None` when not, and Port(n) is Port(...) takes a literal: Port is a subtype, and an Int computed when the program runs may not satisfy its rule. A validated struct’s literal with a field that is no literal, its call form over a record value, a patch of one ({..span, low: 0}, Struct.update), and a collection subtype’s literal with an element that is no literal or a spread ([1, n] as a Pair), except one of the std non-empty collections above, are errors naming try_from the same way. An operand of a comparison is the exception: a collection literal compared with a value whose type holds a subtype is checked against that type with its subtypes erased when it does not check against it, as a later branch is, so with p a Pair, p == [1, n] compares Lists. A subtype named as a function value, Iter.map(xs, Port), is the error `Port` is a subtype and has no constructor function: its call form `Port(...)` takes only a literal. The names try_from and unchecked are the subtype’s: an inherent block that declares either is an error.

The prelude holds subtypes of the numeric types and of String: NonZeroInt, NonNegativeInt and PositiveInt (NonNegativeInt and NonZeroInt); NonZeroFloat (neither zero nor NaN), NonNegativeFloat and PositiveFloat; NonZeroDecimal, NonNegativeDecimal and PositiveDecimal; and NonEmptyString. It holds generic subtypes of the collections too: NonEmptyList<T>, NonEmptyVector<T>, NonEmptyMap<K, V> and NonEmptySet<T>. Each has functions that need no Maybe because a value is there (NonEmptyList.first, NonEmptyList.max, NonEmptyList.reduce with no starting value, NonEmptyMap.first_entry), functions whose result keeps the guarantee (NonEmptyList.map, NonEmptyList.prepend onto any List, NonEmptyMap.put into any Map, NonEmptySet.union with any Set), a constructor that cannot fail (NonEmptyList.of(first, rest)), and a length or size that is a PositiveInt. Outside the prelude, std::int’s Int64 is the Ints from -2^63 to 2^63 - 1. A std function whose limit is 64 bits takes one, so Int64.try_from(n) checks a computed value before the call. A std function whose argument would otherwise trap or be ignored takes one: Int.pow’s exponent, String.repeat’s count, Int.bit_count’s argument and the digit counts of Int.format and Float.format_percent are NonNegativeInts, so Int.pow(2, -1) is -1 is not a NonNegativeInt: `fn n -> n >= 0` is false; a size that must hold something is a PositiveInt (Channel.buffered’s capacity, Reader.read’s max, Iter.chunks and Iter.windows); and the divisor of a named function that divides is a NonZeroInt (Int.modulo, Int.floor_div) or a NonZeroDecimal (Decimal.divide, Decimal.divide_exact). Two bounds that must agree are one range of the prelude’s range subtypes (§3 Range literals): Int.clamp(n, 0..=11), Generator.int(1..=6), and the digits after the point of Float.format, Decimal.format and Decimal.format_percent, a ClosedRange<NonNegativeInt> (fraction: 0..=2, or Range.from(2) for at least two and every digit past them). Std modules declare subtypes of their own where one argument has a rule: Decimal.allocate and Money.allocate take std::decimal’s Ratios (none negative, not all zero, at least one), Generator.float std::random’s FiniteRange (a range with finite ends), std::csv’s options a Delimiter (no quote, line break, U+FFFD or U+0000), Bits.field std::bits’ FieldBits (a pattern with a field letter) and jwt.sign_as std::json’s JsonObject (a Json.Obj). A computed argument goes through try_from, or a check that narrows it. A std function whose result always satisfies one returns it: a length, size or count (List.length, String.length, Map.size, Iter.count) and an index (Iter.with_index’s, Iter.find_index’s) are NonNegativeInts, and so are Int.abs, Int.gcd and Int.sqrt, so Int.pow(2, List.length(xs)) needs no try_from. A group or a run is a NonEmptyList: Iter.group_by’s values and the elements of Iter.chunks, Iter.windows, Iter.chunk_by and Iter.chunk_equal. Float.abs is a Float, since the absolute value of NaN is NaN, which is no NonNegativeFloat.

Destructuring reads a subtype’s parent, its first when it has several, as it reads a distinct type’s inner value: Positive(x) = p binds a NonNegative.

The std numeric subtypes are the prelude’s NonZeroInt, NonNegativeInt and PositiveInt, their Float and Decimal counterparts, and std::duration’s NonZeroDuration, NonNegativeDuration and PositiveDuration. The compiler knows, of each value of Int, Decimal, Duration and Float where it can, an interval the value lies in, open or unbounded at either end, and whether it is off zero: the value’s range. A value is the narrowest std numeric subtype its range proves: Positive when no value in it is zero or below, NonNegative when none is below zero, NonZero when it excludes zero. With count a NonNegativeInt, count + 1 is a PositiveInt, count + 0 a NonNegativeInt and count - 1 an Int; after if size > 1, size - 1 is a PositiveInt.

A range comes from:

  • a literal, possibly negated: its value;
  • a type: what the std numeric subtypes on its chain state (a PositiveInt is 1 and up), with the bounds of each Int subtype on it whose rule compares its parameter with Int literals (a conjunct of another form bounds nothing); a parameter, a field, an annotated binding and any other value not listed here has its type’s range;
  • a binding with no type written: its value’s, so with k = 60 * 60, k is 3600 wherever it is read;
  • a check of a binding (Narrowing);
  • arithmetic, which is exact (§8 Integer arithmetic is exact, §8 Decimal arithmetic): a + b, a - b, a * b and -a of Ints and of Decimals, and a + b and a - b of Durations and a Duration times an Int, as Int arithmetic on nanoseconds. Of Floats, a + b where neither is below zero is no NaN (an overflow is +inf), at least zero, and above zero when either is, since rounding to nearest takes no such sum below its larger operand; -a is exact. A Float product or difference has no range: the product of two positive values can round to 0.0, and 0.0 * inf and inf - inf are NaN;
  • an Int’s a / b, which truncates toward zero, by a b above zero: between 0 and a, so n / 2 of a non-negative n is non-negative; by a b below zero, between 0 and -a. An Int’s a % b, which takes a’s sign: between 0 and a, and smaller in size than the largest b can be when b is bounded;
  • the branches of an if with an else or of a case, and a block’s last expression: every value a branch that finishes can have;
  • Int.abs, Decimal.abs and Duration.abs: the absolute values of the argument’s range; Int.pow(b, e) and Decimal.pow(b, e): 1 when e is 0, the power when both are one value and it is small enough to work out (Int.pow(2, 63) - 1 is 2^63 - 1), else positive, non-negative or off zero as b is; Int.sqrt(n): the roots of n’s ends; Int.to_decimal(n): n’s range; Duration.as_nanos(d): d’s range; Duration.nanoseconds, microseconds, milliseconds, seconds, minutes and hours: the argument’s range in nanoseconds, so Duration.minutes(p) with p a PositiveInt is a PositiveDuration; String.length, List.length, Vector.length, Map.size, Set.size and Iter.count of a non-empty subtype: positive; Int.max(a, b), Decimal.max and Duration.max: at least the higher of the arguments’ lowest values and at most the higher of their highest, and min the other way round, so Int.max(1, n) is a PositiveInt;
  • an element a std Iter function passes to a callback (below).

Anything else, a Decimal’s / and % and the bitwise operators among them, has its type’s range. A Float’s range holds only of a value that is no NaN, and a Float of none may be NaN. A Duration’s typed literal has none, since the compiler does not read its value. No range relates two values: after i < n, i is no narrower than before.

A value whose range rests on literals alone keeps its base as its type, so 1 + 2 and x after x = 3 are Ints, and List.concat([n], [-1]) is a List<Int>. A check of such a binding (Narrowing) types it by what the check proves of its type alone: after x = 3 and if x < 0 then return, x is still an Int, and its range still rests on literals. An unannotated once is a constant, and its type is the narrowest std numeric subtype its value’s range proves: once k = 60 * 60 is a PositiveInt in every file that reads it.

Where a subtype is expected, a value converts to it when its range proves the subtype’s rules, with nothing run when the program does: a std numeric subtype, an intersection of them, or an Int subtype whose only parent is Int and whose rule is comparisons of its parameter with Int literals joined by and, as std::int’s Int64 is. With k = 60 * 60, Int.pow(2, k) needs no try_from, and with subtype Digit Int when fn n -> n >= 0 and n <= 9, neither does digit(n) after if n >= 0 and n <= 9. A subtype whose rule is of any other form, or whose parent is another subtype, is checked through try_from as before.

A user-declared subtype gets no arithmetic of its own; its value is a value of its ancestors, so with s a subtype Small NonNegativeInt when fn n -> n < 10, s + s is a NonNegativeInt (0 to 18), not a Small.

The elements of some iterables have a range, and a lambda or capture that a std Iter function calls with them takes it for the parameter that receives one: the element of Iter.map, filter, reject, each, find, find_map, find_index, any_match, all_match, flat_map, take_while, drop_while, partition, group_by, count_by, min_by, max_by, sum_by, mean_by, product_by, chunk_by, sort_by and sort_with, and the item of reduce, scan, try_reduce and map_reduce. The parameter keeps its type, an Int here, and converts where its range proves a subtype, as a binding with no type written does. The elements with a range are those of:

  • a range literal of Ints: a..=b from the lowest value a’s range holds to the highest b’s, and a..b below that, so every element of 1..=n is 1 or more and every element of 0..8 is 0 to 7;
  • Range.from(n) and Iter.from(n): n’s lowest value and up; Range.naturals(): 0 and up; Range.step_by(a..=b, by): between a and b, whichever way the step goes;
  • a List, Vector or Set literal with no spread: its elements’ ranges together, a tuple’s part by part;
  • Iter.filter, reject, take, drop, take_while, drop_while, sort, sort_by, sort_with, reverse, to_list, to_vector, to_set and cycle of a source with a range, which pass on elements they keep unchanged; Iter.concat of two; the second part of Iter.with_index’s tuples and each part of Iter.zip’s;
  • Iter.map and Iter.scan: the range of the callback’s result, when its body has no return or break.

A source of any other form, a binding among them, gives its elements no range, and Iter.iterate gives none.

fn divisors(n: PositiveInt) -> List<Int>
    1..=n |> Iter.filter(fn d -> n % d == 0) |> Iter.to_list()
end

fn bits(byte: Int) -> List<Int>
    Iter.map(0..8, &(byte >>> (7 - &1) &&& 1)) |> Iter.to_list()
end

fn main()
    dbg divisors(12) // [1, 2, 3, 4, 6, 12]
    dbg bits(5)      // [0, 0, 0, 0, 0, 1, 0, 1]
end

A check of a parameter or local binding narrows its range in the code the check guards, so a value computed while the program runs needs no try_from there:

fn divide(n: Int, d: Int) -> Maybe<Int>
    if d == 0 then return None
    Some(Int.divide(n, d)) // d is a NonZeroInt here
end

fn first_or(xs: List<Int>, fallback: Int) -> Int
    if xs == [] then
        fallback
    else
        NonEmptyList.first(xs)
    end
end

fn last_index(size: Int) -> PositiveInt
    if size <= 1 then return 1
    size - 1 // size is 2 and up here
end

fn main()
    dbg divide(7, 2)    // Some(3)
    dbg first_or([], 0) // 0
    dbg last_index(4)   // 3
    n = 3
    dbg if n >= 0 then Int.pow(2, n) else 0 // 8
end

A comparison x op k or k op x, with op one of ==, !=, <, <=, > and >=, narrows x, a binding of Int, Decimal, Duration or Float, when k is a constant of its base: a value whose range is one value, a literal, possibly negated, or a binding of one. Where it is true, x > k keeps of x’s range the values above k, x >= k those from k up, x < k and x <= k those below, x == k the value k, and x != k all but k: after n >= 0 and n != 0, n is a PositiveInt, and x != 0 makes x off zero. A comparison of an Int, Decimal or Duration that is false is its opposite that is true: in the else of if n < 0, n >= 0 and n is a NonNegativeInt. A Float comparison but != is false when x is NaN, so a true one also proves x is no NaN, and a false one proves nothing unless x’s range already rules NaN out, except x != k false, which is x == k. So x != 0.0 narrows nothing of a Float that may be NaN, since NonZeroFloat holds no NaN.

Iter.is_empty(x) false, x != e true and x == e false, with e an empty literal, [], {} or "", narrow a List, Vector, Map, Set or String to NonEmptyList, NonEmptyVector, NonEmptyMap, NonEmptySet or NonEmptyString at its type arguments; xs |> Iter.is_empty() is Iter.is_empty(xs).

not c proves what c proves when it has the other value; a and b that is true proves what each proves true, and a or b that is false what each proves false. Two facts about one binding meet. A binding that is a std subtype already narrows further the same way, so a NonNegativeInt checked != 0 is a PositiveInt. A check narrows:

  • the then branch of an if where its condition is true, and the else branch, with each else if after it, where it is false;
  • the right operand of and where the left one is true, and of or where it is false: d != 0 and n % d == 0 is no error;
  • a case arm’s body after its when guard, and in a case with no subject, an arm’s body where its condition is true and every earlier unguarded condition false;
  • the rest of the block after an if whose first branch leaves (return, break, continue, a trap or another expression of type Infallible) where the condition is false, after an if whose else leaves where it is true, after an else if chain with no final else whose branches all leave where every condition is false, and after assert c where c is true and refute c where it is false.

Bindings are immutable, so a narrowed binding holds its value everywhere in that code, a lambda’s body included, and a name rebound there is a new binding with its own type. Nothing else narrows: a value that is no binding (if n + 1 > 0 says nothing of n + 1), a field read, an is test, and a comparison of two bindings neither of which is a constant (a > b). A binding of a user’s subtype keeps its type, though its range narrows: after s > 0 with s a Small, s is a Small that passes where a PositiveInt is expected. A narrowed value is its base at run time, as every subtype’s is.

Taught in Structs, Enums & Distinct Types.

A type with a when rule is a validated type: a new type, which converts to nothing and which nothing converts to, whose values all satisfy the rule. A type whose inner type is a subtype, or an intersection of subtypes, is built the same checked way, against the inner type’s rules.

fn is_email(s: String) -> Bool
    String.contains(s, "@")
end

type Email String when is_email

type UserId PositiveInt

fn user(e: Email) -> String
    Email(s) = e
    s
end

fn main()
    dbg user(Email("a@b.c"))   // "a@b.c"
    dbg Email.try_from("nope") // None
    dbg UserId(5)              // UserId(5)
    dbg UserId.try_from(0)     // None
end

A value enters one through a literal, Email("a@b.c") or UserId(5), checked when the program is compiled as a subtype’s literal is ("nope" is not an Email: `is_email` is false, 0 is not a UserId: UserId wraps PositiveInt, which is a subtype of NonZeroInt, and NonZeroInt's rule `fn n -> n != 0` is false); through T.try_from(x) on a value of the base; through T.unchecked(x) in the declaring file; and, for a type over a subtype with no rule of its own, from a value already of that subtype, UserId(p) with p a PositiveInt. Any other argument of the call form is an error that names try_from on it: UserId(n) with n an Int is UserId(...) takes a literal or a PositiveInt: UserId wraps the subtype PositiveInt, and an Int computed when the program runs may not be one, with the help check the value with `UserId.try_from(n)`, a `Maybe<UserId>` . e: Email = s with s a String is type mismatch: expected Email, got String, whose help names Email.try_from. The call form named as a function value is an error as a subtype’s is. Destructuring, Email(s) = e, reads the inner value as any distinct type’s does. A plain type UserId Int, with no rule anywhere, keeps its plain call form and has no try_from. So does a type whose inner type holds a subtype without being one, type Ids List<PositiveInt>: its call form takes a List<PositiveInt>, whose elements are checked already, as type Contact Email takes an Email. Which types wrap a subtype is decided by what their inner type’s name resolves to, so a subtype another file declares, or names through a typealias, counts as one this file declares does.

A validated type, and a type over a subtype, is declared at the top of a file, as a subtype is, since its try_from comes with an impl and an impl cannot stand in a body. Inside a body, type Local PositiveInt is a type over a subtype is declared at the top of a file: move `Local` out of the body, so that it has `Local.try_from` , and type Code String when is_code is a type with a rule is declared at the top of a file: move `Code` out of the body.

A validated type, and a type over a subtype, implements TryFrom of its base (§12 TryFrom) because of its rule and its base: try_from is TryFrom’s function, with a body the compiler supplies, which checks the base’s rules, then the type’s own, and answers Some or None. A generic one implements it at its parameters: type Short<T> List<T> when fn xs -> List.length(xs) < 3 implements TryFrom<List<T>> for Short<T>. impl TryFrom<Int> for Percent, with type Percent Int when ..., is `TryFrom<Int>` for Percent is supplied by its rule and cannot be implemented; every `type` with a rule over Int satisfies `TryFrom<Int>` automatically — remove this `impl TryFrom<Int> for Percent`. unchecked stays the type’s own function.

Taught in Structs, Enums & Distinct Types.

typealias Name Target makes Name another spelling of Target in type positions. The two are one type, and nothing converts between them since nothing needs to. No = comes between them: typealias Name = Target is a typealias has no `=`: write `typealias X T` . The target may be an intersection: typealias Item Priced and Costed names the interface conjunction, and typealias Both NonNegativeInt and NonZeroInt the intersection of subtypes.

typealias Point {x: Int, y: Int}

fn shift(p: Point) -> Point
    {x: p.x + 1, y: p.y}
end

fn main()
    dbg shift({x: 1, y: 2}) // {x: 2, y: 2}
end

An alias may name any type the file sees, including an alias declared below it. An alias that reaches itself is an error at each alias on the cycle: typealias 'X' refers to itself (X → Y → X).

An alias may take type parameters, which its target names, and bound them with where after the target: typealias Pair<T> (T, T), typealias Sortable<T> List<T> where T: Comparable. A use is the target at the use’s type arguments, Pair<Int> is (Int, Int), and a use whose argument breaks the bound is an error at the use: Sortable<Circle> is Circle does not implement Comparable (required by `where T: Comparable` on typealias Sortable). A use without its arguments, Pair, is typealias Pair takes 1 type argument: write `Pair<T>` .

An alias has no rule, since it is its target under another name: typealias Small Int when fn n -> n < 10 is a typealias has no rule, since it is its target under another name: for the values of Int that satisfy a rule, declare `subtype Small Int when ...` .

Functions do not hang off an alias. impl P, impl Display for P and derive Debug for P, where P is an alias, are errors that name the target (`P` is a typealias for `Pt`; write `impl Pt`), and so is a call through one, P.get(p) (`P` is a typealias for `Pt`; call `Pt.get`).

Taught in Generics.

A struct, enum, distinct type, interface or function may take type parameters, in angle brackets after its name: struct Pair<A, B>, fn first<A>(list: List<A>) -> Maybe<A>. A use writes type arguments the same way (List<String>, Result<User, String>); a call usually infers them (§5). A where clause bounds a type parameter by interfaces (§12 Bounds and dispatch in generic code).

A struct, enum, distinct type, host type or interface may give a type parameter a default type, written after =: pub opaque type Route<P = Unit> String. A use that leaves the argument out takes the default, so Route is Route<Unit>, and Pair<Int> is Pair<Int, String> for struct Pair<A, B = String>.

struct Tagged<T, Tag = String>
    value: T
    tag:   Tag
end

fn label(t: Tagged<Int>) -> String
    "${t.tag}: ${t.value}"
end

fn main()
    dbg label(Tagged{value: 1, tag: "n"}) // "n: 1"
end

The rules:

  • The parameters with a default come after every one without: struct Pair<A = Int, B> is type parameter `B` has no default, so it can't follow `A`, which has one.
  • A default names no type parameter, its own declaration’s or another’s: a type parameter's default can't name a type parameter (`A`). It is resolved where the declaration is, so it may name a type the file using the declaration does not import.
  • A default may name its own declaration only with every argument written. struct Box<T = List<Box<Int>>> is fine, since Box<Int> takes no default. struct Box<T = Box> would expand forever (Box<Box<Box<…>>>) and is an error at the default: `Box`'s default for `T` names `Box` itself, which would never end; write the argument where `Box` is used. The same holds for a cycle through another declaration’s default (struct A<T = B> and struct B<U = A>), reported at one default on it: `B`'s default for `U` names `A`, whose default names `B` again, which would never end; write the argument where `A` is used.
  • A function’s type parameters take none, since a call infers them: a function's type parameter can't have a default; a call infers `T`.
  • A default fills a type position only: an annotation, a parameter or result type, a field’s type, a type argument. There, Route with no arguments is Route<Unit>, never a type to infer: fn to(route: Route) takes only a Route<Unit>, while a generic function’s own type parameter is still inferred at each call. Where a type name stands for the declaration rather than a use of it (an impl or derive header, a struct literal’s or a pattern’s head), it keeps its parameters open as before, and they are solved from the values.
  • A use with too few arguments for the parameters without a default is `Pair` expects 1 to 2 type arguments, got 0.

A type prints with its trailing default arguments left out, in hover and in error messages: a Route<Unit> prints as Route, and a Tagged<Int, String> as Tagged<Int>.

A function’s type parameters are solved at each call from its arguments, then from the type its result is expected to have for those the arguments leave open (§5 Type arguments from the arguments). So each must appear in a parameter’s type, in the return type, or in a where bound on a type parameter that does (fn any<I, T>(items: I) -> Bool where I: Iter<T>). A where bound alone does not count. One that appears nowhere else is an error at its declaration: type parameter `U` is not used in the signature of `f`, so no call can determine it.

A function in an inherent impl Span<T> block may use the block’s T, or declare its own, which shadows it. A function whose signature does not name the block’s T does not depend on it, and a call to it names no instance (Span.seven()). Its body may not name that T either: `T` is `Span`'s type parameter, and `seven`'s signature does not determine it. The same holds in an inherent block on an interface (impl Iter<T>).

A generic function is instantiated for each tuple of type arguments it is called with. A generic function that reaches itself, directly or through others, at a type built from its own type parameter needs infinitely many instances, and is an error at the call that grows the type:

struct Box<T>
    inner: T
end

fn grow<T>(x: T, n: Int) -> Int
    if n == 0 then
        0
    else
        grow(Box{inner: x}, n - 1) // T = Box<T>: an error
    end
end

The error is `grow` instantiates `grow` at `T = Box<T>`, a type that grows on every recursive call, so it needs infinitely many instances (polymorphic recursion); each generic function is instantiated per type, so this is rejected: recurse at the same type parameters, or through a non-generic helper or an interface-typed parameter.

Recursion at the same type parameters, at a concrete type, or with the parameters permuted is allowed.

Type<T> is a prelude type whose value stands for the type T and holds nothing else. A type name is a value of Type<T> where a Type<T> is expected, as a function lets a caller pass a type rather than a value of it:

type TraceId String

fn first_of<T>(xs: List<T>, _type: Type<T>) -> Maybe<T>
    Iter.first(xs)
end

fn main()
    dbg first_of([TraceId("a")], TraceId) // Some(TraceId("a"))
end

Anywhere else a type name is a value only in the forms §4 Distinct Types lists, and otherwise `Int` is a type, not a value. No code builds or reads a Type<T> value. Context.value(c, TraceId) (§15) takes one. Two witnesses are equal when they name the same type (§5 Equality), and one inspects as Type<TraceId>.