1d81c9b0665494ef2acdfc60a3b4c243518121dc5a7a35bdb4a31244eee5f076.tri (2191B)
1 !import prelude * 2 !import io * 3 !export * 4 5 -- Interaction Tree Effect Runtime 6 -- 7 -- The IO system is an interaction-tree effect runtime interpreted by a 8 -- small-step machine with a cooperative scheduler. Primitive actions 9 -- (putStr, readFile, writeFile, ...) are tagged nodes in an interaction 10 -- tree. Sequencing is performed by the single generic `bind` constructor. 11 -- 12 -- pure x -- lift a pure value into IO 13 -- bind action k -- run action, then apply k to its result 14 -- thenIO a b -- run a, discard its result, then run b 15 -- mapIO action f -- run action, then apply f to its result inside pure 16 -- 17 -- The runtime supports several effects beyond basic IO: 18 -- ask -- read the current environment 19 -- local f action -- run action with environment transformed by f 20 -- get -- read the current mutable state 21 -- put s -- replace the mutable state 22 -- fork action -- spawn a concurrent task, returning a handle 23 -- await handle -- wait for a forked task to complete 24 -- yield -- yield control to the scheduler 25 -- sleep ms -- suspend current task for N milliseconds 26 -- 27 -- File operations return a Result tree (see lib/base.tri): 28 -- ok value -- pair true (pair value t) 29 -- err msg -- pair false (pair msg t) 30 -- 31 -- Use onReadFile / onWriteFile for convenient branching. 32 -- 33 -- See demos/interactionTrees/ for smaller focused examples. 34 35 -- Cooperative async demo. 36 -- fork runs an action in the background. 37 -- sleep suspends the current task for N milliseconds. 38 -- await waits for a forked task and returns its value. 39 -- 40 -- Here the child sleeps for 2 s while the parent prints immediately. 41 -- The parent's message appears first, proving interleaving. 42 43 asyncDemo = ( 44 bind (fork 45 (bind (sleep 2000) (_ : 46 bind (putStrLn "2000ms done sleeping!") (_ : 47 pure "child2000 done")))) 48 (handle2000 : 49 bind (fork 50 (bind (sleep 5000) (_ : 51 bind (putStrLn "5000ms done sleeping!") (_ : 52 pure "child5000 done")))) 53 (handle5000 : 54 bind (putStrLn "Parent first!") (_ : 55 bind (await handle5000) (_ : 56 await handle2000))))) 57 58 main = io asyncDemo