import std/io import std/list // `ctl` operations natively (M5 part 3): each handler's body runs on its // own fiber; `resume` continues it once. effect gen { ctl yield :: x: Int -> () } effect ask { ctl ask :: -> Int } effect stop { final ctl stop :: reason: String -> Never } fn count :: i n { if i < n { yield i count (i + 1) n } else { () } } // The sum of everything the action yields. fn total :: action: fn() -> () / -> Int / { handle { action () } with { yield x -> x + resume (), return _ -> 0 } } // The first value yielded; the rest of the action is cancelled (it never // resumes), so what it holds is released. fn first :: action: fn() -> () / -> Int / { handle { action () } with { yield x -> x, return _ -> -1 } } fn guarded :: action: fn() -> Int / -> String / { handle { show (action ()) } with { stop r -> "stopped: " <> r } } pub fn main :: -> () / { // Long enough to be preempted many times inside the fiber. io.println ("sum " <> show (total fn { count 0 20000 })) let held = { use <- first let big = list.range 1 1000 yield (list.length big) io.println "never printed" } io.println ("first " <> show held) // `ask` is forwarded through the inner `gen` handler to the outer one. let forwarded = handle { use <- total yield (ask ()) yield (ask ()) } with { ask -> resume 10 + 1 } io.println ("forwarded " <> show forwarded) // `final ctl` leaves a fiber for a handler outside it. io.println ( guarded fn { use <- total yield 1 stop "from inside a generator" } ) } //> sum 199990000 //> first 1000 //> forwarded 22 //> stopped: from inside a generator