// Early `return` from the function's own blocks (ADR 0037): out of `if`, // `match` arms and guards, nested blocks and expressions; what the blocks // held is released (no leaks natively); `return f(x)` is a tail call, so a // million of them run with a small stack. //@ small-stack import std/io import std/list type Shape { Circle(Int), Rect(Int, Int) } fn sign :: n: Int -> String { if n < 0 { return "negative" } if n == 0 { return "zero" } "positive" } /// The first even number, from a nested block in a `match` arm. fn first_even :: xs: List -> Option { match xs { [] -> None , [x, ..rest] -> { let half = { if x % 2 == 0 { return Some(x) } x / 2 } let _ = half first_even rest } } } /// A field of a value the caller still holds (a borrowed projection), /// returned from under a guard. fn width :: s: Shape names: List -> Int { let label = list.length names match s { Rect(w, _) if w > 100 -> return w , Rect(w, h) -> w * h + label , Circle(r) -> { if r == 0 { return label } r } } } /// `return` alone returns `()`. fn greet :: name: String -> () / { if name == "" { return } io.println "hello {name}" } /// `return` in an expression: the rest of the expression never runs. fn total :: xs: List -> Int { let n = list.fold xs 0 fn acc x { acc + x } + if list.length xs > 3 { return -1 } else { 0 } n * 10 } /// A list that is still alive after the `if`: released when it returns. fn keep :: xs: List stop: Bool -> Int { let copy = ["a", ..xs] if stop { return 0 } list.length copy } fn count_down :: n: Int -> Int { if n > 0 { return count_down (n - 1) } n } pub fn main :: -> () / { io.println "{sign (-3)} {sign 0} {sign 7}" io.println "{first_even [1, 3, 6, 7]} {first_even [1, 3]}" io.println "{width Rect(200, 2) ["a"]} {width Rect(2, 3) ["a"]} {width Circle(0) ["a", "b"]} {width Circle(5) []}" greet "" greet "Ada" io.println "{total [1, 2]} {total [1, 2, 3, 4]}" io.println "{keep ["b"] True} {keep ["b"] False}" io.println "{count_down 1000000}" if True { return } io.println "never printed" } //> negative zero positive //> Some(6) None //> 200 7 2 5 //> hello Ada //> 30 -1 //> 0 2 //> 0