Skip to content

choice — examples

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

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: choice   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 "?" }
    }
}

choice 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: choice   status: verified
// verified behavior: Test.test(...) == "yes"

namespace Test

choice 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: choice   status: verified
// verified behavior: Test.test(...) == 1

namespace Test

choice 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

choice 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: choice   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: choice   status: verified
// verified behavior: Test.test(...) == "num=42|word=foo"

namespace Test

choice 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: choice   status: verified
// verified behavior: Test.test(...) == 42

namespace Test

choice 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: choice   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: choice   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: choice   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: choice   status: verified
// verified behavior: reports diagnostic ES2145

namespace Test

choice C { a  b(n: int) }

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

json

choice authored verified

Showcase example

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: json.es   topic: choice   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 choice`: 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 `data` — copied by value, no identity.
data Field {
    key: string
    value: Json
}

// The recursive value type. `ref choice` = abstract base + one sealed subclass per case;
// the cases reference `Json` (and `List<Json>`) freely because each case is a real class.
ref choice 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))
}

promotion_and_match

choice authored verified

Showcase example

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

namespace Demo

// ═════════════════════════════════════════════════════════════════════════════
// E#'s defining move: behavior lives in FREE FUNCTIONS, but a free function whose
// first parameter is a value `data` is PROMOTED to a method on that type. You write
// plain procedural code; you get to call it object-style — including chaining.
//
//   func add(v: Vec, o: Vec) -> Vec   is the method   Vec.add   →   v.add(o)
//
// The free-call spelling `add(v, o)` is then a hard error (the compiler 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 the function.
//
// This file pairs that with the other half of E#'s type story — a `choice` (a closed
// set of shapes) consumed by `match` (exhaustive pattern dispatch). A `choice` is NOT
// a `data`, so functions over it are ordinary free functions, never promoted.
// ═════════════════════════════════════════════════════════════════════════════

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

// Each of these has `Vec` as its first parameter, so each is promoted onto `Vec`.
// Call them `a.add(b)`, `a.scaled(2)`, `a.dot(b)` — never `add(a, b)`.
func add(v: Vec, o: Vec) -> Vec {
    return Vec { x: v.x + o.x, y: v.y + o.y }
}

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

func dot(v: Vec, 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 combine(a: Vec, 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.
choice Shape {
    point                  // no payload
    segment(length: int)   // one payload
    box(w: int, h: int)    // two payloads
}

// `Shape` is a `choice`, not a `data`, 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 choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
ref choice 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: TranspilerTests.cs::ExhaustiveMatch_No_Warning_When_Complete   topic: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

choice 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_Generic_Choice   topic: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Opt

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

func unwrap<T>(opt: Option<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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Conn

pub choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace SM

pub choice Status { on, off }

pub data Device {
    status: Status
}

pub func check(d: Device) -> 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Conn

pub choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

ref choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

ref choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

ref choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

ref choice 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: choice   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

choice State {
    running(progress: int)
    stopped
}

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

turtle

choice authored verified

Showcase example

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: turtle.es   topic: choice   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 `ref data`: 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 `ref data` 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 `choice` 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 `choice`: `forward` carries how far, `turn`
// carries which way (the `Turn` enum). `match` in `apply` handles both.
choice Command {
    forward(steps: int)
    turn(direction: Turn)
}

// The turtle. `ref data` = 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).
ref data 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 apply(t: Turtle, 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

choice authored verified

Showcase example

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: vending.es   topic: choice   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 `ref data` — a class with reference semantics — as opposed to the
// value `data` used elsewhere in this corpus. Commands arrive as a `choice` (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 `choice`: `insert` carries which coin; the
// others carry nothing.
choice Command {
    insert(coin: Coin)
    buy
    cancel
}

// The machine itself — a `ref data`, because it has identity and evolving state.
// `var` fields mutate in place; `price` is fixed at construction.
ref data 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 `ref data` is one object, not a copy.
func apply(m: Machine, 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 `ref data` — `Program` OWNS the machine and drives the
// session in `main`. A `main` method on a `ref data 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.
ref data 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

choice authored verified

Showcase example

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: vm.es   topic: choice   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 `choice` (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.
choice 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 `ref data 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 `ref data Program` IS the program's entry point; the compiler constructs the program
// (`Program()`) and calls `.main()`, so no separate launcher function is needed.
ref data 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
    }
}

Runs `go` → 2

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::MixedArms_PositionalAndView   topic: choice   status: unverified
// verified behavior: Test.go(...) == 2

func go() -> int {
  let p = Pair2.single(2)
  match (p: Pair2) { .single(s) { return s.x } .couple(a, b) { return a + b } }
  return -1
}

Runs `go` → "num:7"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::NestedView_OneThenInnerMatch   topic: choice   status: unverified
// verified behavior: Test.go(...) == "num:7"

func desc(tok: Token) -> string {
  match (tok: Token) { .word(w) { return "w:{w.text}" } .number(n) { return "num:{n.value}" } }
  return "?"
}
func go() -> string {
  let lx = Lex.one(Token.number(7))
  match (lx: Lex) { .one(o) { return desc(o.t) } .pair(p) { return "pair" } }
  return "?"
}

Runs `go` → "hi/9"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::NestedView_PairProjectsTwoTokens   topic: choice   status: unverified
// verified behavior: Test.go(...) == "hi/9"

func desc(tok: Token) -> string {
  match (tok: Token) { .word(w) { return w.text } .number(n) { let v = n.value
    return "{v}" } }
  return "?"
}
func go() -> string {
  let lx = Lex.pair(Token.word("hi"), Token.number(9))
  match (lx: Lex) { .one(o) { return "one" } .pair(p) { return "{desc(p.a)}/{desc(p.b)}" } }
  return "?"
}

Runs `go` → 3

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::NestedView_SameNameShadowing   topic: choice   status: unverified
// verified behavior: Test.go(...) == 3

func go() -> int {
  let outer = Pair2.couple(1, 2)
  match (outer: Pair2) {
    .single(c) { return c.x }
    .couple(c) {
      let inner = Pair2.single(3)
      match (inner: Pair2) { .single(c) { return c.x } .couple(c) { return c.a } }
      return -2
    }
  }
  return -1
}

Runs `go` → 7

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::Positional_SinglePayload_UsedBare   topic: choice   status: unverified
// verified behavior: Test.go(...) == 7

func go() -> int {
  let t = Token.number(7)
  match (t: Token) { .word(w) { return 0 } .number(n) { return n } }
  return -1
}

Runs `go` → 6

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::Positional_ThreePayloads   topic: choice   status: unverified
// verified behavior: Test.go(...) == 6

func go() -> int {
  let t = Triple.only(1, 2, 3)
  match (t: Triple) { .only(a, b, c) { return a + b + c } }
  return -1
}

Runs `go` → 30

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::Positional_TwoPayloads   topic: choice   status: unverified
// verified behavior: Test.go(...) == 30

func go() -> int {
  let p = Pair2.couple(10, 20)
  match (p: Pair2) { .single(x) { return x } .couple(a, b) { return a + b } }
  return -1
}

Runs `go` → 14

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::ResultOfChoice_ViewProjection   topic: choice   status: unverified
// verified behavior: Test.go(...) == 14

func fetch() -> Result<Reply, string> = ok(Reply.accepted(7))
func go() -> int {
  let r = fetch()?
  match (r: Reply) { .accepted(a) { return a.id * 2 } .rejected(x) { return 0 } }
  return -1
}

Runs `go` → "v=42"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::SinglePayloadView_InInterpolation   topic: choice   status: unverified
// verified behavior: Test.go(...) == "v=42"

func go() -> string {
  let p = Pair2.single(42)
  match (p: Pair2) { .single(s) { return "v={s.x}" } .couple(c) { return "?" } }
  return "?"
}

Runs `go` → 11

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::View_InMatchExpression   topic: choice   status: unverified
// verified behavior: Test.go(...) == 11

func go() -> int {
  let p = Pair2.couple(5, 6)
  return match (p: Pair2) { .single(s) { s.x } .couple(c) { c.a + c.b } }
}

Runs `go` → 30

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::View_MultiPayload_BothFields   topic: choice   status: unverified
// verified behavior: Test.go(...) == 30

func go() -> int {
  let p = Pair2.couple(10, 20)
  match (p: Pair2) { .single(x) { return x } .couple(c) { return c.a + c.b } }
  return -1
}

Runs `go` → 10

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::View_MultiPayload_FieldA   topic: choice   status: unverified
// verified behavior: Test.go(...) == 10

func go() -> int {
  let p = Pair2.couple(10, 20)
  match (p: Pair2) { .single(x) { return x } .couple(c) { return c.a } }
  return -1
}

Runs `go` → 20

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::View_MultiPayload_FieldB   topic: choice   status: unverified
// verified behavior: Test.go(...) == 20

func go() -> int {
  let p = Pair2.couple(10, 20)
  match (p: Pair2) { .single(x) { return x } .couple(c) { return c.b } }
  return -1
}

Runs `go` → 7

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_CaseView.cs::View_MultiPayload_FieldOrderIndependent   topic: choice   status: unverified
// verified behavior: Test.go(...) == 7

func go() -> int {
  let p = Pair2.couple(3, 4)
  match (p: Pair2) { .single(x) { return x } .couple(c) { let b = c.b
    let a = c.a
    return a + b } }
  return -1
}