Skip to content
Playground(another site)

Validate and transform

Reps.of(n) checks a raw Int against the refinement — here, that it falls in the range 1 to 100 — and returns a Result. This is the bridge from untrusted input to a refined value: the validation happens once, explicitly, and produces either the constrained value or an error.

The ? operator then does the routing. It unwraps a success in place, or returns the error from the enclosing function early, so everything after let r = Reps.of(n)? only ever sees a value that has already passed the check. Choose Edit & run in-page below (or open it in the playground) and press Run to follow one value from raw Int to validated Reps, and another that fails the check.

validate-and-transform.bynk
context demo
---
`Reps.of(n)` validates an `Int` against the refinement and returns a `Result`.
The `?` operator unwraps the success or returns the error early, so the rest of
the function only ever sees a value that already passed the check.
---
type Reps = Int where InRange(1, 100)
fn doubled(n: Int) -> Result[Int, ValidationError] {
let r = Reps.of(n)?
Ok(r * 2)
}
---
Run calls `service playground`: `21` passes the check and is doubled, and `500`
stops at `?` with the `ValidationError`.
---
service playground {
on call() -> Effect[List[String]] by Caller {
[21, 500].map((n) => match doubled(n) {
Ok(d) => "\(n) doubled is \(d)"
Err(e) => "\(n): \(e.message)"
})
}
}