Synsema docsENES

Control de flujo y errores

control.syn
-- Doc example: control flow (when / match / each) and errors (try / recover / raise).
intent: "doc example: control flow and errors"

task grade(score)
    when score >= 90
        give "A"
    otherwise when score >= 70
        give "B"
    otherwise
        give "C"

task label_of(status)
    match status
        is "open"
            give "active"
        is "done"
            give "archived"
        otherwise
            give "unknown"

task sum_list(xs)
    let total be 0
    each n in xs
        set total to total + n
    give total

task always_fails()
    raise("boom")

print("grade(85) = " + grade(85) + ",  sum_list([1,2,3]) = " + text(sum_list([1, 2, 3])))

test "when / otherwise when / otherwise"
    assert_eq(grade(95), "A")
    assert_eq(grade(75), "B")
    assert_eq(grade(50), "C")

test "match dispatches on value"
    assert_eq(label_of("open"), "active")
    assert_eq(label_of("done"), "archived")
    assert_eq(label_of("x"), "unknown")

test "each accumulates"
    assert_eq(sum_list([1, 2, 3, 4]), 10)

test "try / recover catches; raise re-raises"
    let caught be ""
    try
        raise("boom")
    recover err
        set caught to err
    assert(contains(caught, "boom"))
    assert_error(always_fails)

Condicionales

when score >= 90
    give "A"
otherwise when score >= 70
    give "B"
otherwise
    give "C"

match

match despacha sobre un valor con patrones ricos — literales, variantes de enum, patrones de list/map, guardas y _:

match result
    is {status: 200, body}          -- campo de map + binder
        use(body)
    is [first, ...rest]             -- cabeza + cola de lista
        handle(first)
    is _                            -- comodín
        skip()
    otherwise
        fallback()

Loops

each item in collection itera; while condition repite. Preferí las operaciones intencionales (apply/where/reduce) cuando estás transformando una lista.

Errores — try / recover / raise

try
    risky()
recover err
    log "falló: " + err             -- err es el mensaje (text)
    raise(err)                      -- RE-PROPAGA; sin esto, recover se traga el error

raise(mensaje) falla a propósito. give y stop no son errores — pasan por try/recover sin tocarse. (fail(...) es para respuestas HTTP, no para errores de runtime.)