// Early `return` across a `use` callback, `defer`, `handle` and `region` // bodies (ADR 0037): the function is left through the code in between, // whose cleanups run once, and nothing leaks. import std/io import std/list import std/ref import std/result /// The first number over 10, found inside a `use` callback. fn first_big :: xs: List -> Option { { use x <- list.each xs if x > 10 { return Some(x) } } None } fn parse :: s: String -> Result { match s { "one" -> Ok(1), "two" -> Ok(2), _ -> Error("not a number: {s}") } } /// Nested `use`s: a `return` in the inner callback leaves both. fn sum :: a: String b: String -> Result { use x <- result.try (parse a) use y <- result.try (parse b) if x == y { return Error("the same number twice") } Ok(x + y) } /// The cleanup runs once, whichever way the body is left. fn guarded :: n: Int -> String / { defer { io.println "cleanup for {n}" } if n < 0 { return "negative" } "fine" } effect ask { ctl ask :: -> Int } /// Out of a `handle` body: the handler's `return` clause doesn't run. fn answered :: limit: Int -> String { let n = handle { let answer = ask () if answer > limit { return "too big: {answer}" } answer } with { ask -> resume 42, return v -> v * 10 } "answered {n}" } /// Out of a `region`, with a reference created inside. fn counted :: xs: List stop: Int -> Int { region { let total = ref.new 0 list.each xs fn x { ref.set total (ref.get total + x) } if ref.get total > stop { return -1 } ref.get total } } effect amb { multi ctl choose :: -> Bool } fn all :: action: fn() -> a / -> List / { handle { [action ()] } with { choose -> list.append (resume True) (resume False) } } /// A multi-shot handler inside the function: a `return` from one branch /// leaves the function, and the other branch never runs. fn first_choice :: -> List { let results = all fn { if choose () { "left" } else { "right" } } { use r <- list.each results return [r, "first"] } [] } pub fn main :: -> () / { io.println "{first_big [3, 12, 40]} {first_big [1, 2]}" io.println "{sum "one" "two"} {sum "two" "two"} {sum "one" "six"}" io.println (guarded (-1)) io.println (guarded 1) io.println "{answered 100} / {answered 10}" io.println "{counted [1, 2, 3] 10} {counted [5, 6, 7] 10}" io.println "{first_choice ()}" } //> Some(12) None //> Ok(3) Error(the same number twice) Error(not a number: six) //> cleanup for -1 //> negative //> cleanup for 1 //> fine //> answered 420 / too big: 42 //> 6 -1 //> [left, first]