Molten

Unions and switch

String literal unions

A union of string literals is a small set of named values. It compiles to a C enum, so it is as cheap as an int.

type State = "idle" | "run" | "jump";

function next(running: bool): State { return running ? "run" : "idle"; }

export function main(): void {
    let state = next(false);
    switch (state) {
        case "idle":
        case "jump": print("rest"); break;
        case "run": print("move"); break;
    }
    state = "jump";
    print(state, state == "jump");
}
rest
jump true

A literal gets its union type from where it is used (a typed variable, parameter or return value).

Discriminated unions

A union of object shapes that each have a string literal kind field compiles to a C tagged union. Check kind to narrow it:

type Event =
    | { kind: "damage", amount: int, id: int }
    | { kind: "heal", points: int, id: int }
    | { kind: "quit", id: int };

function describe(event: Event): void {
    print(event.id);                       // every variant has id: no narrowing needed
    switch (event.kind) {
        case "damage": print("damage", event.amount); break;
        case "heal": print("heal", event.points); break;
        case "quit": print("quit"); break;
    }
}

export function main(): void {
    describe({ kind: "damage", amount: 4, id: 1 });
    describe({ kind: "heal", points: 8, id: 2 });
    const e: Event = { kind: "quit", id: 3 };
    if (e.kind == "quit") print("bye");
}
1
damage 4
2
heal 8
bye
  • kind is read-only.
  • A field that exists with the same type in every variant can be read without narrowing. Other fields need narrowing: narrow the union before accessing 'amount'.
  • An object literal must have every field of its variant: missing union property 'amount'.
  • Narrowing works on local variables and parameters.

switch

  • A switch over a union must handle every member or have a default; otherwise switch is not exhaustive.
  • Cases fall through to the next one unless you break (as in TypeScript), and each case has its own scope.
  • switch also works on numbers and strings.

A result instead of exceptions

Cast has no throw. Return a nullable value, or a union that carries the error:

type Parsed =
    | { kind: "ok", value: int }
    | { kind: "error", message: string };

function parseDigit(text: string): Parsed {
    if (text == "7") return { kind: "ok", value: 7 };
    return { kind: "error", message: `not a digit I know: ${text}` };
}

export function main(): void {
    const r = parseDigit("x");
    switch (r.kind) {
        case "ok": print(r.value); break;
        case "error": print(r.message); break;
    }
}
not a digit I know: x

View this page's source on GitHub