soma.cell

Control flow

Control flow, in the reference of the Soma programming language (soma 3.2.4). A block marked ✓ is a whole program that soma check accepts; the others are excerpts.

if condition {
    // ...
} else if other {
    // ...
} else {
    // ...
}

while condition {
    if done { break }
    if skip { continue }
}

for item in list(1, 2, 3) {
    print(item)
}

for i in range(0, 10) {
    // 0 to 9
}

// A Map iterates {key, value} entries; a String iterates its non-empty LINES
// (`for line in read_file(p)`), so a one-line string is one element — for the
// characters write `for c in split(s, "")`. `()` has no elements; an Int is refused.
for e in map("a", 1) {
    print(e.key + " = " + to_string(e.value))
}

match value {
    "a" -> expr1
    "b" -> { stmts; expr2 }
    42 -> expr3
    () -> expr4              // match null
    "x" || "y" -> expr5     // or-pattern
    name -> use(name)        // variable binding (captures value)
    "/api/" + rest -> api(rest) // string prefix pattern
    {method: "GET", path} -> get(path) // map destructuring: every named key must be present
    _ -> default_expr        // wildcard
}

// Map destructuring with nested patterns
match request {
    {method: "GET", path: "/"} -> home()
    {method: "POST", path: "/api/" + resource} -> create(resource)
    {method: "DELETE", path: "/api/" + resource} -> delete(resource)
    _ -> response(404, map("error", "not found"))
}

// Guard clauses
match score {
    n if n >= 90 -> "A"
    n if n >= 80 -> "B"
    n if n >= 70 -> "C"
    _ -> "F"
}

// Range patterns
match http_status {
    200..299 -> "success"
    300..399 -> "redirect"
    400..499 -> "client error"
    500..599 -> "server error"
    _ -> "unknown"
}

// If/match as expressions
let x = if cond { a } else { b }
let y = match status {
    "on" -> true
    _ -> false
}