Skip to content

union — examples

← all topics · 179 examples · page 3 of 4 · raw source ↓

Runs `test` → "hola"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests2.cs::Match_Expression_StringLiteral   topic: union   status: verified
// verified behavior: Test.test(...) == "hola"

namespace Test

func greet(lang: string) -> string = match lang {
    "en" { "hello" }
    "es" { "hola" }
    default { "hi" }
}

func test() -> string {
    return greet("es")
}

Runs `test` → "level: medium"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests2.cs::Match_ExpressionBody_ResultInInterpolation   topic: union   status: verified
// verified behavior: Test.test(...) == "level: medium"

namespace Test

func levelName(n: int) -> string = match n {
    1 { "low" }
    2 { "medium" }
    default { "?" }
}

func test() -> string {
    let name = levelName(2)
    return "level: {name}"
}

Runs `test` → "medium,hola,CRIT,ok,seven,negative"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests2.cs::Sample_MatchPatterns_Full   topic: union   status: verified
// verified behavior: Test.test(...) == "medium,hola,CRIT,ok,seven,negative"

namespace Test

func levelName(n: int) -> string = match n {
    1 { "low" }
    2 { "medium" }
    3 { "high" }
    default { "unknown" }
}

func greet(lang: string) -> string = match lang {
    "en" { "hello" }
    "es" { "hola" }
    "fr" { "bonjour" }
    default { "hi" }
}

enum Priority {
    low = 1
    medium = 5
    high = 10
    critical = 100
}

func priorityLabel(p: Priority) -> string {
    match (p: Priority) {
        .low { return "LOW" }
        .medium { return "MED" }
        .high { return "HIGH" }
        .critical { return "CRIT" }
        default { return "?" }
    }
}

union Result {
    ok(value: int)
    err(message: string)
}

func unwrap(r: Result) -> string = match r {
    .ok(v) { "ok" }
    .err(msg) { "err" }
    default { "?" }
}

enum Color {
    red
    green = 10
    blue
}

func test() -> string {
    let a = levelName(2)
    let b = greet("es")
    let c = priorityLabel(Priority.critical())
    let d = unwrap(Result.ok(42))
    let x = 7
    let tag = match x {
        1 { "one" }
        7 { "seven" }
        default { "other" }
    }
    let n = -1
    let sign = match n {
        -1 { "negative" }
        0 { "zero" }
        1 { "positive" }
        default { "other" }
    }
    return "{a},{b},{c},{d},{tag},{sign}"
}

Runs `test` → "yes"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests3.cs::Choice_Bare_Variants_Default_Arm   topic: union   status: verified
// verified behavior: Test.test(...) == "yes"

namespace Test

union Light { off, on }

func test() -> string {
    let l = Light.on()
    match (l: Light) {
        .on { return "yes" }
        default { return "no" }
    }
    return "unreachable"
}

Runs `test` → 1

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests3.cs::Choice_Helper_Constructs_Variant   topic: union   status: verified
// verified behavior: Test.test(...) == 1

namespace Test

union Status { idle, busy }

func make_busy() -> Status = Status.busy()

func test() -> int {
    let s = make_busy()
    match (s: Status) {
        .busy { return 1 }
        default { return 0 }
    }
    return -1
}

ILEmitterTests3__Match_Bool_Patterns

union runnable verified

Runs `state` → "off"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests3.cs::Match_Bool_Patterns   topic: union   status: verified
// verified behavior: Test.state(...) == "off"

namespace Test

func state(b: bool) -> string = match b {
    true { "on" }
    false { "off" }
}

Runs `test` → "num=42|word=foo"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests3.cs::Match_Choice_Multiple_Variants_With_Payloads   topic: union   status: verified
// verified behavior: Test.test(...) == "num=42|word=foo"

namespace Test

union Token {
    plus
    minus
    number(value: int)
    word(name: string)
}

func describe(t: Token) -> string = match (t: Token) {
    .plus { "+" }
    .minus { "-" }
    .number(n) { "num=" + n.ToString() }
    .word(w) { "word=" + w }
    default { "?" }
}

func test() -> string {
    return describe(Token.number(42)) + "|" + describe(Token.word("foo"))
}

Runs `test` → 42

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests3.cs::Match_Choice_With_Payload_Destructures   topic: union   status: verified
// verified behavior: Test.test(...) == 42

namespace Test

union Maybe {
    none
    some(value: int)
}

func unwrap(m: Maybe, def: int) -> int = match (m: Maybe) {
    .none { def }
    .some(v) { v }
    default { def }
}

func test() -> int = unwrap(Maybe.some(42), 0)

Runs `describe` → "fail"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests3.cs::Match_Expression_Returns_Value   topic: union   status: verified
// verified behavior: Test.describe(...) == "fail"

namespace Test

enum Code { ok, warn, fail }

func describe(c: Code) -> string = match (c: Code) {
    .ok { "ok" }
    .warn { "warn" }
    .fail { "fail" }
    default { "?" }
}

Runs `http` → "unknown"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests3.cs::Match_Literal_Int_Patterns   topic: union   status: verified
// verified behavior: Test.http(...) == "unknown"

namespace Test

func http(code: int) -> string = match code {
    200 { "ok" }
    404 { "not found" }
    500 { "server error" }
    default { "unknown" }
}

Runs `role` → 0

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests3.cs::Match_Literal_String_Patterns   topic: union   status: verified
// verified behavior: Test.role(...) == 0

namespace Test

func role(name: string) -> int = match name {
    "admin" { 100 }
    "guest" { 1 }
    default { 0 }
}

Rejected at compile time: ES2145

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: IndexDiagnosticTests.cs::IndexingChoice_Errors   topic: union   status: verified
// verified behavior: reports diagnostic ES2145

namespace Test

union C { a  b(n: int) }

func f(c: C) -> int { return c[0] }

json

union authored verified

Showcase example

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: json.es   topic: union   status: verified
// hand-authored, idiomatic E# — verified through the E# compiler

namespace Demo

using "System.Text"                    // StringBuilder

// ═════════════════════════════════════════════════════════════════════════════
// A JSON value, modeled and serialized. The shape of JSON is a recursive sum type —
// a value is null, a bool, a number, a string, an array OF values, or an object whose
// fields hold values — so it is a `ref union`: an identity-carrying tagged union whose
// cases can recurse through each other (an array holds a `List<Json>`, and so on).
//
// `stringify` is the whole point: one `match` over the six cases, each arm building its
// own text, the array/object arms recursing back into `stringify`. This is the canonical
// "interpreter over an AST" shape — `match` for dispatch, recursion for structure, a
// `StringBuilder` for the O(n) join, string interpolation for the leaves.
// ═════════════════════════════════════════════════════════════════════════════

// One key/value entry of an object. A plain value `struct` — copied by value, no identity.
struct Field {
    key: string
    value: Json
}

// The recursive value type. `ref union` = abstract base + one sealed subclass per case;
// the cases reference `Json` (and `List<Json>`) freely because each case is a real class.
ref union Json {
    jnull
    jbool(value: bool)
    jnum(value: double)
    jstr(value: string)
    jarr(items: List<Json>)
    jobj(fields: List<Field>)
}

// Serialize any value to its JSON text. Exhaustive `match` — every case is handled, so
// the compiler needs no trailing fallback. Each single-payload case binds its payload
// *transparently*: in `.jbool(b)` the name `b` IS the bool, in `.jarr(items)` `items` IS
// the `List<Json>` — the case view unwraps to the payload value (and `b.value` /
// `items.Count` still work). The array/object arms walk their collection and recurse.
//
// The transparent binding is pure SUGAR. A single-payload arm `.jbool(b) { … b … }` is
// exactly the case view `.jbool(c) { … c.value … }` with the projection elided — both
// lower to the identical IL (cast to the variant subclass, then load the one payload
// field). So `.jbool(b)` and `.jbool(c)` + `c.value` are interchangeable; the bare name
// is just the common case spelled shorter. (A multi-payload case has no single value to
// unwrap to, so it keeps the explicit view: `.jobj(c)` then `c.fields`.)
func stringify(j: Json) -> string {
    match j {
        .jnull       { return "null" }
        .jbool(b)    { return b ? "true" : "false" }
        .jnum(n)     { return "{n}" }
        .jstr(s)     { return "\"{s}\"" }
        .jarr(items) {
            let sb = StringBuilder()
            sb.Append("[")
            var i = 0
            while i < items.Count {
                if i > 0 { sb.Append(",") }
                sb.Append(stringify(items[i]))       // recurse into each element
                i += 1
            }
            sb.Append("]")
            return sb.ToString()
        }
        .jobj(fields) {
            let sb = StringBuilder()
            sb.Append("{")
            var i = 0
            while i < fields.Count {
                let f = fields[i]
                if i > 0 { sb.Append(",") }
                sb.Append("\"{f.key}\":")
                sb.Append(stringify(f.value))        // recurse into each value
                i += 1
            }
            sb.Append("}")
            return sb.ToString()
        }
    }
}

// Build a small document and render it:  {"name":"ada","tags":["math","engine"],"active":true}
func main() -> string {
    let tags = List<Json>()
    tags.Add(Json.jstr("math"))
    tags.Add(Json.jstr("engine"))

    let fields = List<Field>()
    fields.Add(Field { key: "name", value: Json.jstr("ada") })
    fields.Add(Field { key: "tags", value: Json.jarr(tags) })
    fields.Add(Field { key: "active", value: Json.jbool(true) })

    return stringify(Json.jobj(fields))
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: MatchTypePatternTests.cs::NilArm_MatchesAbsentValue   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
func classify(o: object) -> string = match o {
        nil     => "nil"
        default => "some"
    }
func go() -> string {
    let x: object = nil
    return classify(x)
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: MatchTypePatternTests.cs::TypePattern_OpenWorld_Object_UnboxesValueType   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
func classify(o: object) -> string = match o {
        (n: int) => "int {n}"
        default  => "other"
    }
func go() -> string = classify(7)

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: MatchTypePatternTests.cs::TypePattern_OpenWorld_Object_WithNilAndDefault   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
func classify(o: object) -> string = match o {
        nil         => "nil"
        (n: int)    => "int {n}"
        (s: string) => "str {s}"
        default     => "other"
    }
func go() -> string = classify("hello")

Rejected at compile time: ES2172

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: MatchTypePatternTests.cs::TypePattern_OverChoice_IsRejected   topic: union   status: verified
// verified behavior: reports diagnostic ES2172

namespace Test
union C { a  b }
func f(c: C) -> int {
    match c {
        (x: int) => 1
        default  => 0
    }
}

Runs `go` → 15

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: MultiLineParamsTests.cs::Choice_Payloads_MultiLine   topic: union   status: verified
// verified behavior: Test.go(...) == 15

namespace Test
union Op {
    add(
        a: int,
        b: int,
    )
    neg(v: int)
}
func eval(o: Op) -> int = match o {
    .add(a, b) => a + b
    .neg(v)    => 0 - v
}
func go() -> int = eval(Op.add(7, 8))

promotion_and_match

union authored verified

Showcase example

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: promotion_and_match.es   topic: union   status: verified
// hand-authored, idiomatic E# — verified through the E# compiler

namespace Demo

// ═════════════════════════════════════════════════════════════════════════════
// E#'s method model: behavior attaches to a type through a Go-style RECEIVER block.
// A function written `func (v: Vec) add(o: Vec)` is a method on `Vec`. You still write
// plain procedural code at namespace scope; the receiver block is what makes a function
// a method — and methods chain.
//
//   func (v: Vec) add(o: Vec) -> Vec   is the method   Vec.add   →   v.add(o)
//
// The free-call spelling `add(v, o)` is a hard error (ES2142 points you at `v.add(o)`).
// The method travels with its receiver type, so it is reachable wherever `Vec` is,
// regardless of which file declared it.
//
// This file pairs that with the other half of E#'s type story — a `union` (a closed
// set of shapes) consumed by `match` (exhaustive pattern dispatch). A function over a
// `union` takes it as an ordinary parameter (no receiver block), so it stays a free
// function — called `f(x)`, never `x.f()`.
// ═════════════════════════════════════════════════════════════════════════════

// A 2-D vector. A `struct` is value-semantic: copying it copies the fields, and a
// function that returns a new `Vec` never disturbs its input.
struct Vec {
    x: int
    y: int
}

// Each of these is declared with a `Vec` receiver block, so each is a method on `Vec`.
// Call them `a.add(b)`, `a.scaled(2)`, `a.dot(b)` — never `add(a, b)`.
func (v: Vec) add(o: Vec) -> Vec {
    return Vec { x: v.x + o.x, y: v.y + o.y }
}

func (v: Vec) scaled(k: int) -> Vec {
    return Vec { x: v.x * k, y: v.y * k }
}

func (v: Vec) dot(o: Vec) -> int {
    return v.x * o.x + v.y * o.y
}

// Because `add` and `scaled` return a `Vec`, promoted calls CHAIN: each result is a
// fresh value you can call the next method on. No mutation, no aliasing — just values
// flowing through transformations.
func (a: Vec) combine(b: Vec) -> Vec {
    return a.add(b).scaled(2)
}

// The other half of the type story: a sum type. Each variant may carry payload fields.
union Shape {
    point                  // no payload
    segment(length: int)   // one payload
    box(w: int, h: int)    // two payloads
}

// `Shape` is a `union`, not a `struct`, so this is a plain free function — call it
// `area(s)`. `match` must cover every variant (the compiler warns otherwise); each
// arm binds that variant's payloads positionally.
func area(s: Shape) -> int {
    match s {
        .point { return 0 }
        .segment(len) { return 0 }      // a 1-D segment has no area
        .box(w, h) { return w * h }
    }
    return 0
}

func main() -> int {
    let a = Vec { x: 1, y: 2 }
    let b = Vec { x: 3, y: 4 }

    let c = a.combine(b)         // (a + b) then *2  →  Vec { x: 8, y: 12 } — promoted, so `a.combine(b)`
    let d = a.dot(b)             // 1*3 + 2*4 = 11

    // Construct a union value with its factory, then fold it with `match`.
    let boxArea = area(Shape.box(3, 5))   // 15

    return c.x + c.y + d + boxArea         // 8 + 12 + 11 + 15 = 46
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: RefChoiceCaseViewTests.cs::MultiPayload_CaseView_StillWorks   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref union E { lit(value: int)  add(left: E, right: E) }
func eval(e: E) -> int {
    match e {
        .lit(v)  { return v }
        .add(n)  { return eval(n.left) + eval(n.right) }
    }
}
func go() -> int = eval(E.add(E.lit(5), E.lit(7)))

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: RefChoiceCaseViewTests.cs::MultiPayload_Positional_StillWorks   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref union E { lit(value: int)  add(left: E, right: E) }
func eval(e: E) -> int {
    match e {
        .lit(v)    { return v }
        .add(l, r) { return eval(l) + eval(r) }
    }
}
func go() -> int = eval(E.add(E.lit(8), E.lit(12)))

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: RefChoiceCaseViewTests.cs::SinglePayload_BareName_IsPayloadValue   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref union E { lit(value: int)  neg(inner: E) }
func eval(e: E) -> int {
    match e {
        .lit(v)   { return v }
        .neg(inner) { return 0 - eval(inner) }
    }
}
func go() -> int = eval(E.lit(42))

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: RefChoiceCaseViewTests.cs::SinglePayload_BoolTransparent   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref union Flag { on(value: bool)  off }
func read(f: Flag) -> bool {
    match f {
        .on(v) { return v }
        .off   { return false }
    }
}
func go() -> bool = read(Flag.on(true))

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: RefChoiceCaseViewTests.cs::SinglePayload_DotField_StillResolves   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref union Box { full(value: int)  empty }
func read(b: Box) -> int {
    match b {
        .full(c) { return c.value }   // c.value still works (aliases the bare binding)
        .empty   { return 0 }
    }
}
func go() -> int = read(Box.full(9))

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: RefChoiceCaseViewTests.cs::SinglePayload_ListTransparent_Indexing   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref union Seq { arr(items: List<int>)  empty }
func total(s: Seq) -> int {
    match s {
        .arr(items) {
            var sum = 0
            var i = 0
            while i < items.Count {
                sum += items[i]
                i += 1
            }
            return sum
        }
        .empty { return 0 }
    }
}
func go() -> int {
    let xs = List<int>()
    xs.Add(10)
    xs.Add(20)
    return total(Seq.arr(xs))
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: RefChoiceCaseViewTests.cs::SinglePayload_Recursion_ThroughBareName   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref union E { lit(value: int)  neg(inner: E) }
func eval(e: E) -> int {
    match e {
        .lit(v)     { return v }
        .neg(inner) { return 0 - eval(inner) }
    }
}
func go() -> int = eval(E.neg(E.lit(7)))

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: RequiredDeconstructTests.cs::ConstructionBatch_EndToEnd   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

struct Span {
    required lo: int
    required hi: int
}

struct Vec2(x: int, y: int)

class Conn(
    host: string
    port: int = 80,
) {
    var label: string = host
    init { if port == 0 { label = "invalid" } }
    init(host: string) : this(host, 8080) { }
    func describe() -> string { return self.label + ":" + port.ToString() }
}

func run() -> string {
    let primary = Conn(port: 443, host: "api")
    let secondary = Conn("dev")
    // Arity-1 has two surfaces: the secondary init (exact match) and the
    // primary with its port default. The zero-defaults match wins.
    let defaulted = Conn("plain")
    let s = Span { lo: 1, hi: 5 }
    let (x, y) = Vec2(s.lo, s.hi)
    let head = primary.describe() + " " + secondary.describe()
    return head + " " + defaulted.describe() + " " + (x + y).ToString()
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: SemanticModelTests.cs::CaseOccurrences_DeclarationAndDotCaseUse_SameSymbol   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
union Shape {
    circle(r: int)
    square(side: int)
}
func make() -> Shape = .circle(2)

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::ExhaustiveMatch_No_Warning_When_Complete   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

union Light {
    red
    yellow
    green
}

func check(l: Light) -> int {
    match (l: Light) {
        .red { return 1 }
        .yellow { return 2 }
        .green { return 3 }
    }
    return 0
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::ExhaustiveMatch_No_Warning_With_Default   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

union Light {
    red
    yellow
    green
}

func check(l: Light) -> int {
    match (l: Light) {
        .red { return 1 }
        default { return 0 }
    }
    return 0
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::ExhaustiveMatch_Warns_Missing_Cases   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

union Light {
    red
    yellow
    green
}

func check(l: Light) -> int {
    match (l: Light) {
        .red { return 1 }
        .yellow { return 2 }
    }
    return 0
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_Data_Choice_And_Functions   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Auth

pub struct LoginRequest {
    email: string
    password: string
}

pub union AuthError {
    invalidCredentials
    accountLocked(untilUtc: DateTimeOffset)
}

pub func makeRequest(email: string, password: string) -> LoginRequest {
    let req = LoginRequest {
        email: email
        password: password
    }
    return req
}

pub func (req: LoginRequest) login() -> Result<LoginRequest, AuthError> {
    if req.password == "secret" {
        return ok(req)
    }

    return error(AuthError.invalidCredentials())
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_Generic_Choice   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Opt

union Option<T> {
    some(value: T)
    none
}

func (opt: Option<T>) unwrap<T>(fallback: T) -> T {
    match (opt: Option<T>) {
        .some(value) { return value }
        default { return fallback }
    }
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_Match_On_Choice_Annotated   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Conn

pub union ConnectionState {
    disconnected
    connected
    failed(reason: string)
}

pub func describe(state: ConnectionState) -> string {
    match (state: ConnectionState) {
        .disconnected { return "off" }
        .connected { return "on" }
        .failed(reason) { return reason }
        default { return "?" }
    }
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_Match_On_MemberAccess_Inferred   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace SM

pub union Status { on, off }

pub struct Device {
    status: Status
}

pub func (d: Device) check() -> string {
    match d.status {
        .on { return "on" }
        .off { return "off" }
        default { return "?" }
    }
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_Match_Without_Annotation   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Conn

pub union ConnectionState {
    disconnected
    connected
}

pub func describe(state: ConnectionState) -> string {
    match state {
        .disconnected { return "off" }
        .connected { return "on" }
        default { return "?" }
    }
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_MultiPayload_Destructuring   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

union Action {
    popout(containerId: uint, slotIndex: int)
    close
}

func handle(a: Action) -> int {
    match (a: Action) {
        .popout(cid, slot) { return 1 }
        .close { return 0 }
    }
    return 0
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_MultiPayload_RefChoice   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

ref union Action {
    popout(containerId: uint, slotIndex: int)
    close
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_MultiPayload_ValueChoice   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

union Msg {
    text(from: string, body: string)
    ping
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_RefChoice_DotCase   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

ref union Option {
    some(value: int)
    none
}

func make() -> Option {
    return .some(42)
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_RefChoice_Match   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

ref union Shape {
    circle(radius: float)
    square(side: float)
}

func describe(s: Shape) -> string {
    match (s: Shape) {
        .circle(c) { return "circle" }
        .square(sq) { return "square" }
    }
    return "unknown"
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_RefChoice_SealedHierarchy   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

ref union Expr {
    literal(value: int)
    negate(inner: Expr)
    unit
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_SinglePayload_Destructuring_BackwardCompat   topic: union   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

union State {
    running(progress: int)
    stopped
}

func check(s: State) -> int {
    match (s: State) {
        .running(p) { return p }
        .stopped { return 0 }
    }
    return 0
}

turtle

union authored verified

Showcase example

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: turtle.es   topic: union   status: verified
// hand-authored, idiomatic E# — verified through the E# compiler

namespace Demo

// ═════════════════════════════════════════════════════════════════════════════
// A turtle you drive with a CHAIN of commands — the fluent-builder pattern, and the
// reason it works.
//
// The turtle is a `class`: it has identity and evolving state (position + heading).
// Each command is applied by `apply`, which mutates the turtle and then **returns the
// turtle itself**. Because a `class` is a reference, returning it hands back the SAME
// object — so `apply` can be chained, and you never re-name the receiver:
//
//     Turtle().apply(...).apply(...).apply(...)
//
// That return-`self` move is the whole trick behind fluent APIs (`StringBuilder`,
// LINQ, query builders). Contrast it with a method that returns a `Result` or a fresh
// value: those don't chain, because the next call would land on the wrong type.
//
// The commands themselves show the other half of the language: a `union` whose
// `forward` case carries a step count and whose `turn` case carries an `enum`
// direction, dispatched with `match`. One `apply`, two payload shapes, no `if`-ladder.
// ═════════════════════════════════════════════════════════════════════════════

// Which way to pivot. A plain `enum` — a closed set of named constants.
enum Turn {
    left
    right
}

// What the turtle can be told to do. A `union`: `forward` carries how far, `turn`
// carries which way (the `Turn` enum). `match` in `apply` handles both.
union Command {
    forward(steps: int)
    turn(direction: Turn)
}

// The turtle. `class` = identity + mutable state; heading is 0=N, 1=E, 2=S, 3=W,
// so a right turn is +1 (mod 4) and a left turn is +3 (mod 4).
class Turtle {
    var x: int
    var y: int
    var facing: int

    init() {
        self.x = 0
        self.y = 0
        self.facing = 0          // start facing North
    }
}

// Apply one command and RETURN THE TURTLE — that return-self is what makes `apply`
// chainable. `match` dispatches the command; `forward` walks in the current heading,
// `turn` rotates. The nested `match (direction: Turn)` folds the enum to a delta.
func (t: Turtle) apply(cmd: Command) -> Turtle {
    match cmd {
        .forward(steps) {
            if t.facing == 0 { t.y += steps }          // North
            else if t.facing == 1 { t.x += steps }     // East
            else if t.facing == 2 { t.y -= steps }     // South
            else { t.x -= steps }                       // West
        }
        .turn(direction) {
            match (direction: Turn) {
                .left  { t.facing = (t.facing + 3) % 4 }
                .right { t.facing = (t.facing + 1) % 4 }
            }
        }
    }
    return t        // the SAME turtle — the chain continues on it
}

// Drive the turtle with a single fluent chain — no intermediate `t` rebinding, just
// commands flowing through the one object:
//
//   start (0,0) facing N
//   forward 5 → (0,5)        turn right → facing E
//   forward 3 → (3,5)        turn right → facing S
//   forward 2 → (3,3)
//
// Final position (3, 3) → encoded as x*100 + y = 303.
func main() -> int {
    let t = Turtle()
        .apply(Command.forward(5))
        .apply(Command.turn(Turn.right()))
        .apply(Command.forward(3))
        .apply(Command.turn(Turn.right()))
        .apply(Command.forward(2))

    return t.x * 100 + t.y      // 303
}

vending

union authored verified

Showcase example

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: vending.es   topic: union   status: verified
// hand-authored, idiomatic E# — verified through the E# compiler

namespace Demo

// ═════════════════════════════════════════════════════════════════════════════
// A vending machine — a small stateful protocol, and the one place E# reaches for
// the object world on purpose.
//
// The machine HAS IDENTITY: there is one of it, money accumulates in it, stock
// depletes from it, and every command acts on that same evolving thing. That is the
// definition of `class` — a class with reference semantics — as opposed to the
// value `struct` used elsewhere in this corpus. Commands arrive as a `union` (insert a
// coin, buy, cancel) and are dispatched with `match`. Coins are an `enum` with
// explicit denominations, decoded by a second `match`. Anything the user can get
// wrong (too little credit, sold out) is a `Result`, so the caller always gets a
// clear outcome instead of a silent failure.
// ═════════════════════════════════════════════════════════════════════════════

// Coin denominations, in cents. An `enum` emits as a real CLR enum; the explicit
// values are the actual coin worth.
enum Coin {
    nickel  = 5
    dime    = 10
    quarter = 25
}

// Decode a coin to its cent value. `match` over an enum needs the type named so the
// `.nickel` shorthand resolves to `Coin`.
func cents(c: Coin) -> int {
    match (c: Coin) {
        .nickel  { return 5 }
        .dime    { return 10 }
        .quarter { return 25 }
    }
    return 0
}

// The three things a customer can do. A `union`: `insert` carries which coin; the
// others carry nothing.
union Command {
    insert(coin: Coin)
    buy
    cancel
}

// The machine itself — a `class`, because it has identity and evolving state.
// `var` fields mutate in place; `price` is fixed at construction.
class Machine {
    var credit: int
    var stock: int
    let price: int

    init(stock: int, price: int) {
        self.credit = 0
        self.stock = stock
        self.price = price
    }
}

// Apply one command to the machine, mutating it and reporting the outcome. Promoted
// onto `Machine` (first parameter), so the caller writes `machine.apply(cmd)`. Each
// arm reads/writes the shared state through the reference — the changes persist
// across calls because a `class` is one object, not a copy.
func (m: Machine) apply(cmd: Command) -> Result<string, string> {
    match cmd {
        .insert(coin) {
            m.credit += cents(coin)               // coin IS the Coin (transparent view)
            return ok("credit: {m.credit}c")
        }
        .buy {
            if m.stock == 0 {
                return error("sold out")
            }
            if m.credit < m.price {
                return error("need {m.price - m.credit}c more")
            }
            let change = m.credit - m.price
            m.credit = 0                          // bank the price, return the rest
            m.stock -= 1
            return ok("dispensed — change {change}c, {m.stock} left")
        }
        .cancel {
            let refund = m.credit
            m.credit = 0
            return ok("refunded {refund}c")
        }
    }
}

// A short session against ONE machine: the mutations accumulate because `m` is a
// single identity-bearing object, not re-copied each call. Two quarters + a dime is
// 60c against a 50c price → dispensed with 10c change.
// The application is itself a `class` — `Program` OWNS the machine and drives the
// session in `main`. A `main` method on a `class Program` IS the program's entry
// point (the class-style alternative to a bare top-level `func main`); the compiler
// constructs the program (`Program()`) and calls `.main()`, so no launcher is needed.
class Program {
    func main() -> string {
        let m = Machine(3, 50)                // 3 items, 50c each

        m.apply(Command.insert(Coin.quarter())) // credit 25
        m.apply(Command.insert(Coin.quarter())) // credit 50
        m.apply(Command.insert(Coin.dime()))    // credit 60

        let result = m.apply(Command.buy())     // dispense, 10c change, 2 left
        return result.IsOk ? result.Value : "error: {result.Error}"
    }
}

vm

union authored verified

Showcase example

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: vm.es   topic: union   status: verified
// hand-authored, idiomatic E# — verified through the E# compiler

namespace Demo

// ═════════════════════════════════════════════════════════════════════════════
// A tiny stack machine — the smallest thing that is honestly a "virtual machine".
//
// A program is a list of instructions; execution is a loop that walks them, each
// one pushing to or popping from an operand stack. This is how real bytecode VMs
// (the CLR's own, the JVM, CPython, Lua) work underneath — just with more opcodes.
//
// The instruction set is a `union` (a value tagged union): some variants carry a
// payload (`push` carries the integer to push), most carry none (`add`, `dup`, …).
// Executing one instruction is a `match` over the variant — the canonical use of a
// sum type. The operand stack is a `List<int>` used as a LIFO: `Add` is push,
// `xs[xs.Count - 1]` is peek, `RemoveAt(xs.Count - 1)` is pop — a `List<T>` from the
// BCL, called directly. Anything that can fail (popping an empty stack, dividing by
// zero, leaving the wrong number of results) is a `Result`, threaded with `?`.
// ═════════════════════════════════════════════════════════════════════════════

// The instruction set. `push` is the only variant with a payload.
union Op {
    push(value: int)
    add
    sub
    mul
    div
    dup        // duplicate the top of the stack
    swap       // exchange the top two
}

// Pop the top of the stack, or fail on underflow. Takes `*List<int>`... actually a
// `List<int>` is already a reference type, so it is passed and mutated directly — no
// pointer needed. Returns the popped value (or an error), leaving the list shorter.
func pop(stack: List<int>) -> Result<int, string> {
    if stack.Count == 0 {
        return error("stack underflow")
    }
    let top = stack[stack.Count - 1]
    stack.RemoveAt(stack.Count - 1)
    return ok(top)
}

// Execute one instruction against the stack. `match` covers every variant, so the
// dispatch is exhaustive; each arm either pushes, or pops its operands (with `?`
// propagating an underflow) and pushes the result. Single-payload `push` binds its
// value transparently — `n` IS the int.
func step(stack: List<int>, op: Op) -> Result<int, string> {
    match op {
        .push(n) { stack.Add(n) }
        .add {
            let b = pop(stack)?
            let a = pop(stack)?
            stack.Add(a + b)
        }
        .sub {
            let b = pop(stack)?
            let a = pop(stack)?
            stack.Add(a - b)
        }
        .mul {
            let b = pop(stack)?
            let a = pop(stack)?
            stack.Add(a * b)
        }
        .div {
            let b = pop(stack)?
            let a = pop(stack)?
            if b == 0 {
                return error("division by zero")
            }
            stack.Add(a / b)
        }
        .dup {
            let top = pop(stack)?
            stack.Add(top)
            stack.Add(top)
        }
        .swap {
            let b = pop(stack)?
            let a = pop(stack)?
            stack.Add(b)
            stack.Add(a)
        }
    }
    return ok(0)        // step's value is unused; it reports success or the error
}

// Run a whole program: step through every instruction, then require exactly one value
// left on the stack — that's the result. Too many or too few is a program error, not a
// silent answer.
func run(program: List<Op>) -> Result<int, string> {
    let stack = List<int>()
    var i = 0
    while i < program.Count {
        step(stack, program[i])?      // propagate the first runtime error
        i += 1
    }
    if stack.Count != 1 {
        return error("program left {stack.Count} values on the stack, expected 1")
    }
    return ok(stack[0])
}

// Build and run:  (2 + 3) * (10 - 6)  ==  5 * 4  ==  20
//   push 2, push 3, add        → stack [5]
//   push 10, push 6, sub       → stack [5, 4]
//   mul                        → stack [20]
// The entry point lives on a `class Program` — the OO "an object IS the application"
// shape, the class-style alternative to a bare top-level `func main`. A `main` method on
// a `class Program` IS the program's entry point; the compiler constructs the program
// (`Program()`) and calls `.main()`, so no separate launcher function is needed.
class Program {
    func main() -> int {
        let program = List<Op>()
        program.Add(Op.push(2))
        program.Add(Op.push(3))
        program.Add(Op.add())
        program.Add(Op.push(10))
        program.Add(Op.push(6))
        program.Add(Op.sub())
        program.Add(Op.mul())

        let r = run(program)
        return r.IsOk ? r.Value : -1      // 20
    }
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: HierarchyExhaustivenessTests.cs::Default_SuppressesWarning   topic: union   status: unverified
// compiles cleanly (no auto-run claim was extracted)

func go() -> int {
    let s: Sym = TypeSym("a", 1)
    match s {
        (t: TypeSym) { return t.arity }
        default      { return -1 }
    }
}

Runs `go` → "type a/1"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: HierarchyExhaustivenessTests.cs::FullCoverage_NeedsNoDefault_AndSatisfiesDefiniteReturn   topic: union   status: unverified
// verified behavior: Test.go(...) == "type a/1"

func go() -> string {
    let s: Sym = TypeSym("a", 1)
    match s {
        (t: TypeSym)   { return "type {t.name}/{t.arity}" }
        (m: MethodSym) { return "func {m.name}" }
    }
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: HierarchyExhaustivenessTests.cs::FullCoverage_NoWarning   topic: union   status: unverified
// compiles cleanly (no auto-run claim was extracted)

func go() -> string {
    let s: Sym = TypeSym("a", 1)
    match s {
        (t: TypeSym)   { return "type {t.name}" }
        (m: MethodSym) { return "func {m.name}" }
    }
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: HierarchyExhaustivenessTests.cs::GuardedArm_DoesNotCount_AsCoverage   topic: union   status: unverified
// compiles cleanly (no auto-run claim was extracted)

func go() -> string {
    let s: Sym = TypeSym("a", 1)
    return match s {
        (t: TypeSym)                 => "type {t.name}"
        (m: MethodSym) if m.isStatic => "static {m.name}"
    }
}