import std/io import std/list import std/ref effect log { fn log :: msg: String -> () } effect ask { fn ask :: -> Int } effect gen { ctl yield :: x: Int -> () } effect fail { final ctl fail :: reason: String -> Never } fn with_prefix :: prefix: String action: fn() -> a / -> a / { handle { action () } with { log m -> io.println (prefix <> m) } } fn numbers :: { yield 1 yield 2 yield 3 } fn collect :: action: fn() -> () / -> List / { handle { action () } with { yield x -> [x, ..resume ()], return _ -> [] } } fn safe_div :: a b { if b == 0 { fail "division by zero" } else { a / b } } fn attempt :: action: fn() -> a / -> Result / { handle { Ok(action ()) } with { fail reason -> Error(reason) } } fn render :: r { match r { Ok(v) -> "ok " <> show v, Error(e) -> "failed: " <> e } } // Installs its own `log` handler for its internal messages (silenced). fn quietly :: action: fn() -> () / -> () / { handle { log "internal detail" action () } with { log m -> () } } pub fn main :: -> () / { // fn operations resume implicitly. { use <- with_prefix "[log] " log "starting" log "done" } let answer = handle { ask () + ask () } with { ask -> 21 } io.println ("answer " <> show answer) // ctl operations capture the rest of the body. io.println (show (collect numbers)) // final ctl abandons the body. io.println ( render (attempt fn { safe_div 10 2 }) <> "; " <> render (attempt fn { safe_div 1 0 }) ) // An inner handler forwards other effects to outer ones (here: `st` // to the region, `ask` to the outer handler). let total = region { let counter = ref.new 0 handle { handle { log "inside" ref.set counter (ref.get counter + ask ()) } with { log m -> io.println ("inner log: " <> m) } } with { ask -> 5 } ref.get counter } io.println ("counter " <> show total) // A handler can stop early: only the first two yields are kept. let first_two = handle { numbers () [] } with { yield x -> if x > 2 { [] } else { [x, ..resume ()] } } io.println (show (list.length first_two) <> " kept") // Lexical scoping (ADR 0010): the callback's `log` goes to the handler // visible where it is written, not to the one `quietly` installs. { use <- with_prefix "[outer] " use <- quietly log "from the callback" } // Handler clauses run outside their handler: a clause performing its own // effect reaches the next handler out. use <- with_prefix "[outer] " handle { log "relayed" } with { log m -> log ("relay: " <> m) } } //> [log] starting //> [log] done //> answer 42 //> [1, 2, 3] //> ok 5; failed: division by zero //> inner log: inside //> counter 5 //> 2 kept //> [outer] from the callback //> [outer] relay: relayed