Skip to content

choice — examples

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

calculator

choice authored verified

Showcase example

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

namespace Demo

// ═════════════════════════════════════════════════════════════════════════════
// A tiny arithmetic calculator, end to end.
//
// It turns a string like "1 + 2 * 3" into a number — and gets 7, not 9, because it
// respects operator precedence (multiplication binds tighter than addition). It is
// written the way a real E# program is: a recursive-descent parser that builds an
// abstract syntax tree (AST), then a recursive evaluator that walks it.
//
// If this is the first E# you have ever read, here is the whole tour in one file:
//
//   • `ref choice`  — a tagged union (a "sum type"). The AST is one of three shapes:
//                     a number, an addition, or a multiplication. Because it is a
//                     *ref* choice it is a reference type, so a variant may hold
//                     another `Expr` and the tree can nest to any depth.
//   • `data` + `*P` — a small mutable parser-state struct. `data` is a value type
//                     (copying it copies the bits), so to let every parse step share
//                     and advance ONE cursor we put it on the heap with `new`, which
//                     hands back a pointer, written `*P`.
//   • `new`         — the heap-allocation operator: `new P { ... }` allocates a value
//                     `data` on the heap and yields a `*P`. It is the only way to mint
//                     a fresh pointer.
//   • `Result<T,E>` — error handling without exceptions. A parse step returns either
//                     `ok(tree)` or `error("message")`. The `?` after a call means
//                     "if that was an error, stop and return the same error from here",
//                     so the happy path stays flat and readable.
//   • `match`       — exhaustive, binding pattern dispatch over a choice's variants.
// ═════════════════════════════════════════════════════════════════════════════

// The AST. Each variant carries its own payload. `add` and `mul` hold two more
// `Expr`s — legal because `ref choice` is a reference type, so the tree nests freely.
ref choice Expr {
    num(value: int)               // a literal integer, e.g. 42
    add(left: Expr, right: Expr)  // left + right
    mul(left: Expr, right: Expr)  // left * right
}

// The parser's mutable state: the input text plus a cursor into it. It is a value
// type (`data`), but we will hand around a *pointer* (`*P`) so every parse step
// advances the same shared `pos` instead of mutating a private copy.
data P {
    var src: string
    var pos: int
}

// --- small cursor helpers -----------------------------------------------------
// Each takes `*P` (a pointer). A pointer parameter is NOT promoted to a method, so
// these stay plain free functions you call as `atEnd(p)` — only a direct `data`
// receiver (e.g. `func f(v: Vec)`) would become `v.f()`.

// True once the cursor has consumed the whole string.
func atEnd(p: *P) -> bool {
    return p.pos >= p.src.Length
}

// Advance past spaces so the grammar can ignore whitespace.
func skipWs(p: *P) {
    while !atEnd(p) {
        if p.src[p.pos] == ' ' {
            p.pos += 1
        } else {
            return
        }
    }
}

// --- the grammar, highest-precedence first ------------------------------------
//
//   expr   = term   ('+' term)*     (addition — lowest precedence)
//   term   = factor ('*' factor)*   (multiplication — binds tighter)
//   factor = number                 (a run of digits)
//
// Each rule returns `Result<Expr, string>`: the parsed subtree, or an error message.

// factor = number
func parseFactor(p: *P) -> Result<Expr, string> {
    skipWs(p)
    if atEnd(p) { return error("expected a number") }
    if !char.IsDigit(p.src[p.pos]) { return error("expected a digit") }
    let start = p.pos
    while !atEnd(p) && char.IsDigit(p.src[p.pos]) {
        p.pos += 1
    }
    let text = p.src.Substring(start, p.pos - start)
    return ok(Expr.num(int.Parse(text)))
}

// term = factor ('*' factor)*  — left-associative: fold each '*' into the tree.
func parseTerm(p: *P) -> Result<Expr, string> {
    var left = parseFactor(p)?        // `?` unwraps ok, or returns the error from here
    while true {
        skipWs(p)
        if atEnd(p) || p.src[p.pos] != '*' {
            return ok(left)
        }
        p.pos += 1
        let right = parseFactor(p)?
        left = Expr.mul(left, right)
    }
    return ok(left)
}

// expr = term ('+' term)*  — same shape, one precedence level down.
func parseExpr(p: *P) -> Result<Expr, string> {
    var left = parseTerm(p)?
    while true {
        skipWs(p)
        if atEnd(p) || p.src[p.pos] != '+' {
            return ok(left)
        }
        p.pos += 1
        let right = parseTerm(p)?
        left = Expr.add(left, right)
    }
    return ok(left)
}

// Entry point: put the cursor on the heap with `new`, parse a whole expression, and
// confirm nothing is left over.
func parse(src: string) -> Result<Expr, string> {
    var p: *P = new P { src: src, pos: 0 }   // `new` → heap value `data`, yields *P
    let tree = parseExpr(p)?
    skipWs(p)
    if !atEnd(p) {
        return error("trailing characters")
    }
    return ok(tree)
}

// --- evaluation ---------------------------------------------------------------

// Walk the tree to an int. `match` dispatches on the variant and binds a "case view"
// — `.add(n)` gives an `n` whose members are that variant's payloads, reached by their
// declared names (`n.left`, `n.right`, `n.value`). Recursion follows the tree's shape.
func eval(e: Expr) -> int {     // `Expr` is a choice → not promoted → a free function
    match e {
        .num(n) { return n.value }
        .add(n) { return eval(n.left) + eval(n.right) }
        .mul(n) { return eval(n.left) * eval(n.right) }
    }
    return 0
}

// Parse, then evaluate. Returns the answer, or -1 if the input did not parse — so the
// precedence is visible in the result: 1 + 2 * 3 == 7, never 9.
func calc(src: string) -> int {
    let r = parse(src)
    if r.IsError {
        return -1
    }
    return eval(r.Value)
}

// The entry point is a `main` method on a `ref data Program` (the OO application shape,
// the class-style alternative to a bare top-level `func main`). That method IS the entry
// point; the compiler constructs the program (`Program()`) and calls `.main()`.
ref data Program {
    func main() -> int {
        return calc("1 + 2 * 3")    // 7
    }
}

Runs `describe` → "err:nope"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: FeatureMixingTests.cs::Axis5_NestedChoiceInChoiceInResult_FullMatch   topic: choice   status: verified
// verified behavior: Test.describe(...) == "err:nope"

namespace Test

choice Token {
    word(text: string)
    number(value: int)
}

choice Lex {
    one(t: Token)
    pair(a: Token, b: Token)
}

func parse(input: string) -> Result<Lex, string> {
    if input == "fail" { return error("nope") }
    if input == "num" { return ok(Lex.one(Token.number(7))) }
    return ok(Lex.pair(Token.word("hi"), Token.number(9)))
}

func describe(input: string) -> string {
    let r = parse(input)
    match (r: Result<Lex, string>) {
        .ok(lex) {
            match (lex: Lex) {
                .one(o) {
                    match (o.t: Token) {
                        .word(w) { return "one-word:{w.text}" }
                        .number(n) { return "one-num:{n.value}" }
                    }
                }
                .pair(p) {
                    var first = ""
                    match (p.a: Token) {
                        .word(w) { first = "w:{w.text}" }
                        .number(n) { first = "n:{n.value}" }
                    }
                    var second = ""
                    match (p.b: Token) {
                        .word(w) { second = "w:{w.text}" }
                        .number(n) { second = "n:{n.value}" }
                    }
                    return "pair:{first},{second}"
                }
            }
        }
        .err(e) { return "err:{e}" }
    }
    return "?"
}

Compiles

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

namespace Test

choice Reply {
    accepted(id: int)
    rejected(reason: string)
}

func fetch() -> Result<Reply, string> = ok(Reply.accepted(7))

func process() -> Result<int, string> {
    let r = fetch()?
    match (r: Reply) {
        .accepted(a) { return ok(a.id * 2) }
        .rejected(_) { return error("nope") }
    }
    return error("unreachable")
}

Runs `run3` → "?nope"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: FeatureMixingTests.cs::MiniProgram_CliArgRouter   topic: choice   status: verified
// verified behavior: Test.run3(...) == "?nope"

namespace Test

choice Cmd {
    help
    add(a: int, b: int)
    greet(name: string)
    unknown(name: string)
}

func parseCmd(args: List<string>) -> Cmd {
    if args.Count == 0 { return Cmd.help() }
    let head = args[0]
    if head == "help" { return Cmd.help() }
    if head == "add" {
        if args.Count < 3 { return Cmd.unknown("add: need 2 args") }
        return Cmd.add(int.Parse(args[1]), int.Parse(args[2]))
    }
    if head == "greet" {
        let n = args.Count >= 2 ? args[1] : "world"
        return Cmd.greet(n)
    }
    return Cmd.unknown(head)
}

func dispatch(args: List<string>) -> string {
    let c = parseCmd(args)
    match (c: Cmd) {
        .help { return "usage: help|add|greet" }
        .add(a, b) { return "sum={a + b}" }
        .greet(name) { return "hi {name}" }
        .unknown(n) { return "?{n}" }
    }
    return "?"
}

func run1() -> string {
    var args = List<string>()
    args.Add("add")
    args.Add("3")
    args.Add("4")
    return dispatch(args)
}

func run2() -> string {
    var args = List<string>()
    args.Add("greet")
    return dispatch(args)
}

func run3() -> string {
    var args = List<string>()
    args.Add("nope")
    return dispatch(args)
}

Runs `run` → "connected:99|failed:timeout"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: FeatureMixingTests.cs::MiniProgram_ConnectionLifecycleStateMachine   topic: choice   status: verified
// verified behavior: Test.run(...) == "connected:99|failed:timeout"

namespace Test

choice ConnState {
    disconnected
    connecting
    connected(sessionId: int)
    failed(reason: string)
}

data Client {
    var state: ConnState
    name: string
}

func startConnect(c: *Client) -> Result<int, string> {
    match (c.state: ConnState) {
        .disconnected {
            c.state = ConnState.connecting()
            return ok(1)
        }
        .connecting { return error("already connecting") }
        .connected(sid) { return error("already connected") }
        .failed(reason) { return error("in failed: {reason}") }
    }
    return error("unreachable")
}

func markConnected(c: *Client, sid: int) {
    c.state = ConnState.connected(sid)
}

func markFailed(c: *Client, reason: string) {
    c.state = ConnState.failed(reason)
}

func describe(c: *Client) -> string {
    match (c.state: ConnState) {
        .disconnected { return "disconnected" }
        .connecting { return "connecting" }
        .connected(sid) { return "connected:{sid}" }
        .failed(reason) { return "failed:{reason}" }
    }
    return "?"
}

func run() -> string {
    var c: *Client = new Client { state: ConnState.disconnected(), name: "node-1" }
    let r1 = startConnect(c)
    markConnected(c, 99)
    let mid = describe(c)
    markFailed(c, "timeout")
    let end = describe(c)
    return "{mid}|{end}"
}

Compiles

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

namespace Test

ref choice Token {
    integer(value: int)
    str(text: string)
    eof
}

data Lex {
    var src: string
    var pos: int
}

func skipSpace(l: *Lex) {
    while l.pos < l.src.Length {
        let c = l.src[l.pos]
        if c == ' ' || c == '\t' || c == '\n' {
            l.pos += 1
        } else {
            return
        }
    }
}

func nextToken(l: *Lex) -> Result<Token, string> {
    skipSpace(l)
    if l.pos >= l.src.Length { return ok(Token.eof()) }
    let c = l.src[l.pos]
    if c == '"' {
        l.pos += 1
        let start = l.pos
        while l.pos < l.src.Length && l.src[l.pos] != '"' {
            l.pos += 1
        }
        if l.pos >= l.src.Length { return error("unterminated string") }
        let text = l.src.Substring(start, l.pos - start)
        l.pos += 1
        return ok(Token.str(text))
    }
    if char.IsDigit(c) {
        let start = l.pos
        while l.pos < l.src.Length && char.IsDigit(l.src[l.pos]) {
            l.pos += 1
        }
        let text = l.src.Substring(start, l.pos - start)
        return ok(Token.integer(int.Parse(text)))
    }
    return error("unexpected char")
}

func sumIntegersUntilEof(input: string) -> Result<int, string> {
    var l: *Lex = new Lex { src: input, pos: 0 }
    var total = 0
    while true {
        let tok = nextToken(l)?
        match (tok: Token) {
            .integer(i) { total += i.value }
            .str(_) { }
            .eof { return ok(total) }
        }
    }
    return ok(total)
}

Compiles

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

namespace Test
choice Command { forward(steps: int) }
ref data Turtle {
    var y: int
    var facing: int
    init() { self.y = 0  self.facing = 0 }
}
func apply(t: Turtle, cmd: Command) -> Turtle {
    match cmd {
        .forward(steps) {
            if t.facing == 0 { t.y += steps }
        }
    }
    return t
}
func go() -> int {
    let t = Turtle().apply(Command.forward(5)).apply(Command.forward(3))
    return t.y
}

Compiles

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

namespace Test
enum Turn { left  right }
choice Command { turn(direction: Turn) }
ref data Turtle {
    var facing: int
    init() { self.facing = 0 }
}
func apply(t: Turtle, cmd: Command) -> Turtle {
    match cmd {
        .turn(direction) {
            match (direction: Turn) {
                .left  { t.facing = (t.facing + 3) % 4 }
                .right { t.facing = (t.facing + 1) % 4 }
            }
        }
    }
    return t
}
func go() -> int {
    let t = Turtle().apply(Command.turn(Turn.right()))
    return t.facing
}

Compiles

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

namespace Test
enum Turn { left  right }
choice Command { forward(steps: int)  turn(direction: Turn) }
ref data Turtle {
    var x: int
    var y: int
    var facing: int
    init() { self.x = 0  self.y = 0  self.facing = 0 }
}
func apply(t: Turtle, cmd: Command) -> Turtle {
    match cmd {
        .forward(steps) {
            if t.facing == 0 { t.y += steps }
            else if t.facing == 1 { t.x += steps }
            else if t.facing == 2 { t.y -= steps }
            else { t.x -= steps }
        }
        .turn(direction) {
            match (direction: Turn) {
                .left  { t.facing = (t.facing + 3) % 4 }
                .right { t.facing = (t.facing + 1) % 4 }
            }
        }
    }
    return t
}
func go() -> 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
}

Compiles

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

namespace Test
choice Outer { wraps(inner: Inner)  none }
choice Inner { has(n: int)  nothing }
func go() -> int {
    let o = Outer.wraps(Inner.has(11))
    match o {
        .wraps(c) {
            match c.inner {
                .has(x)   { return x }
                .nothing  { return 0 }
            }
        }
        .none { return 0 }
    }
}

Compiles

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

namespace Test
choice Box { full(p: Item)  empty }
data Item { weight: int }
func go() -> int {
    let b = Box.full(Item { weight: 9 })
    match b {
        .full(c) { return c.p.weight }
        .empty   { return 0 }
    }
}

Compiles

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

namespace Test
data Field { key: string, value: J }
ref choice J {
    jnull
    jobj(fields: List<Field>)
}
func go() -> int {
    let fs = List<Field>()
    fs.Add(Field { key: "a", value: J.jnull() })
    fs.Add(Field { key: "b", value: J.jnull() })
    let j = J.jobj(fs)
    match j {
        .jnull    { return 0 }
        .jobj(c)  { return c.fields.Count }
    }
}

Compiles

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

namespace Test
data Wrap { c: Pick }
choice Pick { a(n: int)  b(n: int) }
func go() -> int {
    let w = Wrap { c: Pick.a(5) }
    match w.c {
        .a(x) { return x }
        .b(x) { return x }
    }
}

Compiles

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

namespace Test
data Row { d: Dir }
enum Dir { north  south  east }
func go() -> int {
    let r = Row { d: Dir.east() }
    match r.d {
        .north { return 0 }
        .south { return 1 }
        .east  { return 2 }
    }
}

Compiles

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

namespace Test
using "System.Text"

func render(v: Val) -> string {
    match v {
        .num(c) { return "{c.value}" }
        .arr(c) {
            let sb = StringBuilder()
            sb.Append("[")
            var i = 0
            while i < c.items.Count {
                if i > 0 { sb.Append(",") }
                sb.Append(render(c.items[i]))
                i += 1
            }
            sb.Append("]")
            return sb.ToString()
        }
    }
}

ref choice Val {
    num(value: int)
    arr(items: List<Val>)
}

func go() -> string {
    let xs = List<Val>()
    xs.Add(Val.num(1))
    xs.Add(Val.num(2))
    xs.Add(Val.num(3))
    return render(Val.arr(xs))
}

Compiles

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

namespace Test
ref choice Node { leaf  branch(items: List<Leaf>) }
data Leaf { v: int }
func go() -> int {
    let xs = List<Leaf>()
    xs.Add(Leaf { v: 1 })
    xs.Add(Leaf { v: 2 })
    xs.Add(Leaf { v: 3 })
    let n = Node.branch(xs)
    match n {
        .leaf      { return 0 }
        .branch(c) { return c.items.Count }
    }
}

Compiles

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

namespace Test

choice Option {
    some(value: int)
    none
}

func makeNone() -> Option {
    return Option.none()
}

func makeSome(v: int) -> Option {
    return Option.some(v)
}

Compiles

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

namespace Test

choice Color {
    red
    green
    blue
}

func makeGreen() -> Color {
    return Color.green()
}

Runs `goSquare` → 36

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests.cs::MultiFile_ChoiceInFileA_MatchedInFileB_Works   topic: choice   status: verified
// verified behavior: Test.goSquare(...) == 36

namespace Test

choice Shape {
    circle(r: int)
    square(side: int)
}

Compiles

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

namespace Test

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

func makeText(f: string, b: string) -> Msg {
    return Msg.text(f, b)
}

func makePing() -> Msg {
    return Msg.ping()
}

Compiles

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

namespace Test

choice LogEntry {
    message(level: int, text: string)
    timestamp(epoch: int)
}

func getLevel() -> int {
    let entry = LogEntry.message(3, "hello")
    match (entry: LogEntry) {
        .message(lvl, txt) { return lvl }
        .timestamp(t) { return 0 }
    }
    return -1
}

Compiles

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

namespace Test

ref choice Shape {
    circle(radius: float)
    point
}

func makeCircle() -> Shape {
    return .circle(3.14)
}

func makePoint() -> Shape {
    return .point()
}

Compiles

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

namespace Test

ref choice Shape {
    circle(radius: float)
    rect(width: float)
    point
}

Compiles

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

namespace Test

ref choice Shape {
    circle(radius: float)
    point
}

func describe(s: Shape) -> int {
    match (s: Shape) {
        .circle(c) { return 1 }
        .point { return 0 }
    }
    return 0
}

ILEmitterTests__RefChoice_Match_Runtime

choice unknown verified

Compiles

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

namespace Test

ref choice Expr {
    literal(value: int)
    neg(inner: Expr)
}

func eval(e: Expr) -> int {
    match (e: Expr) {
        .literal(lit) { return lit.value }
        .neg(n) { return 0 - eval(n.inner) }
        default { return 0 }
    }
    return 0
}

Compiles

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

namespace Test

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

func check() -> int {
    let r = Result.ok(42)
    match (r: Result) {
        .ok(v) { return v }
        .err(msg) { return 0 }
    }
    return -1
}

Runs `go` → "N"

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

enum Dir { north south }
func go() -> string {
  let d = Dir.north()
  match (d: Dir) { .north { return "N" } .south { return "S" } }
  return "?"
}

ILEmitterTests_CaseView__ThreeLevel_OnePath

choice runnable verified ×2

Runs `go` → "one-num:7"

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

choice Lex { one(t: Token) pair(a: Token, b: Token) }

Compiles

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

namespace Test

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

func go() -> string = label(true)

Compiles

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

namespace Test

choice Dir { north, south }

func name(d: Dir) -> string {
    match d {
        .north { return "N" }
        .south { return "S" }
    }
}

func go() -> string = name(Dir.south())

Compiles

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

namespace Test

enum Color { red, green, blue }

func code(c: Color) -> int {
    match (c: Color) {
        .red { return 1 }
        .green { return 2 }
        .blue { return 3 }
    }
}

func go() -> int = code(Color.green())

Compiles

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

namespace Test

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

func unwrapOr(o: Option<int>, fallback: int) -> int {
    match o {
        .some(v) { return v }
        .none { return fallback }
    }
    return fallback
}

func go() -> int {
    let a = Option<int>.some(99)
    let b = Option<int>.none()
    return unwrapOr(a, -1) + unwrapOr(b, 5)
}

Compiles

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

namespace Test

func go() -> string {
    let n = 2
    return "v={match n { 1 { "one" } 2 { "two" } default { "?" } }}"
}

Rejected at compile time: ES2160

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Coverage_Adversarial.cs::Ns_SnakeCaseTypeName_IsError   topic: choice   status: verified
// verified behavior: reports diagnostic ES2160

namespace Test

choice my_choice {
    a
    b
}

Runs `go` → 21

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

namespace Test

enum Level {
    a
    b = 10
    c
}

func rank(l: Level) -> int {
    match (l: Level) {
        .a { return 0 }
        .b { return 10 }
        .c { return 11 }
    }
    return -1
}

func go() -> int {
    return rank(Level.a()) + rank(Level.b()) + rank(Level.c())
}

Runs `go` → 40

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

namespace Test

func go() -> int {
    let status = 404
    let label = match status {
        200 { 1 }
        404 { 4 }
        default { 0 }
    }
    return label * 10
}

Runs `go` → 2

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

namespace Test

func classify(n: int) -> int {
    match n {
        200 { return 1 }
        404 { return 2 }
        500 { return 3 }
        default { return 0 }
    }
}

func go() -> int {
    return classify(404) + classify(999)
}

Runs `go` → 8

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

namespace Test

func perm(name: string) -> int {
    match name {
        "admin" { return 7 }
        "guest" { return 1 }
        default { return 0 }
    }
}

func go() -> int {
    return perm("admin") + perm("guest") + perm("other")
}

Runs `go` → 1

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

namespace Test

choice State {
    on
    off
}

data Switch {
    var s: State
}

func describe(sw: Switch) -> int {
    match sw.s {
        .on  { return 1 }
        .off { return 0 }
    }
    return -1
}

func go() -> int {
    let sw = Switch { s: State.on() }
    return sw.describe()
}

Runs `go` → 23

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

namespace Test

ref choice Expr {
    lit(value: int)
    add(left: Expr, right: Expr)
    mul(left: Expr, right: Expr)
}

func eval(e: Expr) -> int {
    match (e: Expr) {
        .lit(v) { return v.value }
        .add(l, r) { return eval(l) + eval(r) }
        .mul(l, r) { return eval(l) * eval(r) }
    }
    return 0
}

func go() -> int {
    let tree = Expr.add(Expr.lit(3), Expr.mul(Expr.lit(4), Expr.lit(5)))
    return eval(tree)
}

Runs `go` → 23

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

namespace Test

ref choice Expr {
    lit(value: int)
    add(left: Expr, right: Expr)
    mul(left: Expr, right: Expr)
}

func eval(e: Expr) -> int {
    match (e: Expr) {
        .lit(v) { return v.value }
        .add(a) { return eval(a.left) + eval(a.right) }
        .mul(m) { return eval(m.left) * eval(m.right) }
    }
    return 0
}

func go() -> int {
    let tree = Expr.add(Expr.lit(3), Expr.mul(Expr.lit(4), Expr.lit(5)))
    return eval(tree)
}

Runs `go` → 2

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

namespace Test

choice Color {
    red
    green
    blue
}

func code(c: Color) -> int {
    match (c: Color) {
        .red   { return 1 }
        .green { return 2 }
        .blue  { return 3 }
    }
    return 0
}

func go() -> int {
    return code(Color.green())
}

Runs `go` → 207

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

namespace Test

choice Entry {
    log(level: int, code: int)
    blank
}

func score(e: Entry) -> int {
    match (e: Entry) {
        .log(lvl, code) { return lvl * 100 + code }
        .blank { return 0 }
    }
    return -1
}

func go() -> int {
    return score(Entry.log(2, 7))
}

Runs `go` → 25

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

namespace Test

choice Shape {
    circle(radius: int)
    square(side: int)
}

func area(s: Shape) -> int {
    match (s: Shape) {
        .circle(r) { return 3 * r * r }
        .square(side) { return side * side }
    }
    return 0
}

func go() -> int {
    return area(Shape.square(5))
}

Compiles

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

namespace Test
choice Sel { a, b, c }
func pick(s: Sel) -> int {
    match s {
        .a { return 1 }
        default { return 99 }
    }
    return 0
}
func go() -> int { return pick(Sel.c()) }

Compiles

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

namespace Test
choice Shape { circle(r: int), square(s: int) }
func area(sh: Shape) -> int {
    match sh {
        .circle(r) { return r }
        .square(s) { return s }
    }
    return 0
}
func go() -> int { return area(Shape.square(5)) }

Compiles

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

namespace Test
data Box { n: int }
choice Sel { a, b }
func go() -> int {
    let s = Sel.a()
    var box = new Box { n: 0 }
    match s {
        .a { box.n = 7 }
        .b { box.n = 9 }
    }
    return box.n
}

Runs `go` → "two"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Coverage_ControlFlow.cs::Match_AsExpression_ExpressionBodiedFunc   topic: choice   status: verified
// verified behavior: Test.go(...) == "two"

namespace Test
func name(n: int) -> string = match n {
    1 { "one" }
    2 { "two" }
    default { "many" }
}
func go() -> string { return name(2) }

Runs `go` → "code=ok"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Coverage_ControlFlow.cs::Match_AsExpression_InInterpolation   topic: choice   status: verified
// verified behavior: Test.go(...) == "code=ok"

namespace Test
func go() -> string {
    let status = 200
    return "code={match status { 200 { "ok" } default { "?" } }}"
}

Runs `go` → "not found"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Coverage_ControlFlow.cs::Match_AsExpression_InLet   topic: choice   status: verified
// verified behavior: Test.go(...) == "not found"

namespace Test
func go() -> string {
    let status = 404
    let label = match status {
        200 { "ok" }
        404 { "not found" }
        default { "other" }
    }
    return label
}