?=
?= binds a successful value and returns early through the enclosing function when the value is absent or failed.
Function Body Only
?= is tied to the enclosing function's return type. Use it as a top-level statement in a function body; it is not valid inside loops, lambdas, or nested callbacks.
pure func first_score(raw_scores: List[String]) -> Result[Int, String]:
first_raw ?= raw_scores
.get(0)
.to_result("missing score")
score ?= first_raw
.parse_int()
.to_result("invalid score")
Ok(score)
-- `?=` must stay at the top level of the enclosing function body.
-- It is not valid inside loops:
-- for raw in raw_scores:
-- score ?= raw.parse_int().to_result("invalid score")
-- It is also not valid inside lambdas:
-- raw_scores.map(func(raw):
-- score ?= raw.parse_int().to_result("invalid score")
-- score
-- )
Without `?=`
When each step can fail, explicit match handling pushes the success path inward.
pure func sum_two(left_raw: String, right_raw: String) -> Result[Int, String]:
match left_raw
.parse_int()
.to_result("invalid left"):
Ok(left):
match right_raw
.parse_int()
.to_result("invalid right"):
Ok(right):
Ok(left + right)
Err(msg):
Err(msg)
Err(msg):
Err(msg)
Result Binding
Inside a function returning Result, ?= unwraps Ok(value) or returns the Err(error) immediately.
pure func sum_two(left_raw: String, right_raw: String) -> Result[Int, String]:
left ?= left_raw
.parse_int()
.to_result("invalid left")
right ?= right_raw
.parse_int()
.to_result("invalid right")
Ok(left + right)
Option Binding
Inside a function returning Option, ?= unwraps Some(value) or returns None immediately.
pure func first_display_name(names: List[String]) -> Option[String]:
name ?= names.get(0)
Some(name.capitalize())
Option-to-Result
to_result turns Option[T] into Result[T, E] before ?= binds the successful value.
func read_greeting() -> Result[String, String]:
name ?= input("name> ").to_result("no input")
Ok("Hello, " + name.trim())
Example
This version uses ?= to keep the success path linear while preserving the same error behavior.
pure func parse_named_int(name: String, raw: String) -> Result[Int, String]:
raw
.parse_int()
.to_result("invalid " + name)
pure func sum_two(left_raw: String, right_raw: String) -> Result[Int, String]:
left ?= parse_named_int("left", left_raw)
right ?= parse_named_int("right", right_raw)
Ok(left + right)
func main(args: List[String]) -> Void:
match sum_two("20", "22"):
Ok(total): print(total) -- prints: 42
Err(msg): print(msg)
Try it
blorp run parse-sum.brp