// Row evidence (ADR 0066): a handler whose operation takes a closure that // performs the effects of its row argument, generic or concrete. import std/io import std/list effect ask { fn ask :: -> Int } effect tell { fn tell :: line: String -> () } effect later { fn later :: render: fn() -> Int / -> Int } fn with_ask :: n: Int action: fn() -> a / -> a / { handle { action () } with { ask -> n } } fn with_tell :: action: fn() -> a / -> a / { handle { action () } with { tell line -> io.println "told: {line}" } } // Runs `render` in place, with the evidence its caller gave for `e`. fn inline :: action: fn() -> a / | e> -> a / { handle { action () } with { later render -> render () } } // Re-installs `ask` around `render`. fn rehandled :: action: fn() -> a / > | e> -> a / { handle { action () } with { later render -> with_ask 100 fn { render () } } } fn page :: -> Int / > | r2> { later fn { ask () + 1 } } fn chatty :: -> Int / >, tell | r2> { tell "before" later fn { tell "inside" ask () } } // Functions with closed rows, called from a part (issue #362). fn twice :: n: Int -> Int { n * 2 } fn shout :: line: String -> () / { tell line } fn plain_calls :: -> Int / > | r2> { later fn { shout (show (list.length [1, 2, 3])) twice (ask ()) } } // A part that itself defers a part. fn nested :: -> Int / > | r1>> | r2> { later fn { later fn { ask () + 10 } } } pub fn main :: -> () / { let a = with_ask 41 fn { inline fn { page () } } io.println "{a}" let b = with_tell fn { with_ask 7 fn { inline fn { chatty () } } } io.println "{b}" let d = with_ask 1 fn { rehandled fn { later fn { ask () } } } io.println "{d}" let n = with_ask 1 fn { inline fn { inline fn { nested () } } } io.println "{n}" // `tell` reaches the part through `inline`'s evidence once `chatty` // is called; a callback inside the part uses it there. let c = with_tell fn { with_ask 5 fn { inline fn { let v = chatty () list.each [1, 2] fn x { tell "after {x}" } v } } } io.println "{c}" let p = with_tell fn { with_ask 4 fn { inline fn { plain_calls () } } } io.println "{p}" } //> 42 //> told: before //> told: inside //> 7 //> 100 //> 11 //> told: before //> told: inside //> told: after 1 //> told: after 2 //> 5 //> told: 3 //> 8