soma.cell

Common patterns

Common patterns, 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.

A complete Soma program: soma check passes on it (soma 3.2.4).

// CRUD web app
cell App {
    memory { items: Map<String, String> [persistent, consistent] }

    on request(method: String, path: String, body: String) {
        if method == "POST" && path == "/api/items" {
            let data = from_json(body)
            let id = to_string(next_id())
            items.set(id, to_json(data |> with("id", id)))
            return data |> with("id", id)
        }
        match path {
            "/api/items" -> items.values |> map(s => from_json(s))
            _ -> response(404, map("error", "not found"))
        }
    }
}

// Data pipeline
cell Pipeline {
    on run() {
        let data = read_csv("input.csv")
        let result = data
            |> filter(s => s.score > 50)
            |> sort_by("score", "desc")
            |> top(10)
        print(result)
    }
}

// Real-time with state machine
cell OrderSystem {
    memory { orders: Map<String, String> [persistent, consistent] }
    state order { initial: pending  pending -> validated  validated -> shipped  * -> cancelled }
    every 30s { check_stale_orders() }

    on create(data: Map) {
        let id = to_string(next_id())
        orders.set(id, to_json(data |> with("id", id) |> with("status", "pending")))
        return map("id", id)
    }

    on advance(id: String, target: String) {
        return transition(id, target)
    }

    on check_stale_orders() {
        for id in orders.keys() {
            if get_status(id) == "pending" { transition(id, "cancelled") }
        }
    }
}