Types, patterns and valuesSlide 25 of 86
25typeTypes, patterns and values

Declared types

Grammar: type-decl, type-body, variant, field
typeIDENT{type-body}
type-decl = "type" IDENT "{" type-body "}" ;
fieldvariant,
type-body = { ( field | variant ) [ "," ] } ;As the compiler reads it; §2.3 of the specification is out of date here.
IDENT{field,}
variant = IDENT [ "{" { field [ "," ] } "}" ] ;As the compiler reads it; §2.3 of the specification is out of date here.
IDENT:typeannotations
field = IDENT ":" type [ annotations ] ;

A type with no variants is a struct; with variants, it is a tagged union. A value is built by calling the type or the variant — User(1, "ada"), Shape.Circle(5) — with its fields in order, or by name in any order. A variant that carries nothing is still called, Shape.Point(), because Shape.Point alone names the variant, not a value of it. There is no subtyping and no interface: a variant is a way to build and match a union, not a type of its own.

A field declared outside every variant is added to all of them, after each variant's own fields, and it is the only kind of field read straight off a union value: event.at. Every other field belongs to its variant and is reached by matching with is, a few slides on — even one that every variant declares under the same name. A union value is built whole, so none of its fields is assigned on its own.

A type may hold itself through a variant, as a tree does, or through a vector. A struct that holds itself directly, or through a Result, could never be finished, and is refused.

A struct
type User {
	id:   Int
	name: Str
}

proc main(): void {
	u := User(1, "ada")
	echo u.name
	echo User(name: "grace", id: 2).id   // by name, in any order
}
A tagged union, and its shared fields
type Event {
	at: Int                  // outside every variant: every one has it
	Opened { by: Str }
	Closed
}

proc main(): void {
	e := Event.Opened("ada", 5)   // the variant's own field first, then `at`
	echo e.at                      // 5 — a shared field is read straight off
	// echo e.by                   // compile error: `by` belongs to Opened

	for each ev in [e, Event.Closed(9)] {
		echo ev.at
	}
}
A type that holds itself
type Expr {
	Num { value: Int }
	Add { left: Expr, right: Expr }
}

type Folder {
	name: Str
	children: Folder[dyn]    // through a vector
}

proc main(): void {
	sum := Expr.Add(Expr.Num(1), Expr.Num(2))
	echo sum
	echo Folder("root", [Folder("docs", [])]).name
}