import std/io import std/process.{type Subject, type proc} // Selectors receive from several subjects at once, each mapped to one type. type Event { Number(Int), Word(String) } fn describe :: e: Event -> String { match e { Number(n) -> "number " <> show n, Word(w) -> "word " <> w } } pub fn main :: -> () / { let numbers: Subject = process.subject () let words: Subject = process.subject () let selector = process.new_selector () |> process.selecting numbers fn n { Number(n) } |> process.selecting words fn w { Word(w) } // Messages arrive in this order; select takes the oldest first. { use <- process.spawn process.send words "hello" process.send numbers 42 process.send words "bye" } io.println (describe (process.select_forever selector)) io.println (describe (process.select_forever selector)) io.println (describe (process.select_forever selector)) // Nothing more: a timeout gives None. io.println (show (process.select selector 50 |> option_text)) // Waiting, then a message arrives on the second subject. { use <- process.spawn process.sleep 10 process.send numbers 7 } io.println (describe (process.select_forever selector)) // A selector on someone else's subject is refused. (A selector holds // functions of its actor, so it cannot be sent: the watcher builds it.) let theirs: Subject = process.receive_forever (spawn_owner ()) let watcher = { use <- process.spawn let other = process.new_selector () |> process.selecting theirs fn n { Number(n) } let _ = process.select other 0 () } let process.Down(_, why) = process.receive_forever (process.monitor watcher) io.println (show why) } fn option_text :: o: Option -> String { match o { Some(e) -> describe e, None -> "nothing" } } /// An actor that creates a subject and hands it back. fn spawn_owner :: -> Subject> / { let back = process.subject () { use <- process.spawn process.send back (process.subject ()) process.sleep 100000 } back } //> word hello //> number 42 //> word bye //> nothing //> number 7 //> Crashed(select on a subject owned by another actor)