IO Semantics
From HaskellWiki
(Difference between revisions)
(Rewritten to remove continuations.) |
|||
| Line 1: | Line 1: | ||
[[Category:Theoretical_foundations]] | [[Category:Theoretical_foundations]] | ||
| - | == Semantics of IO: A | + | == Semantics of IO: A Free Approach == |
The following is inspired by [http://luqui.org/blog/archives/2008/03/29/io-monad-the-continuation-presentation/ Luke Palmer's post]. This only describes one possible semantics of <hask>IO a</hask>; your actually implementation may vary. | The following is inspired by [http://luqui.org/blog/archives/2008/03/29/io-monad-the-continuation-presentation/ Luke Palmer's post]. This only describes one possible semantics of <hask>IO a</hask>; your actually implementation may vary. | ||
Current revision
Semantics of IO: A Free Approach
The following is inspired by Luke Palmer's post. This only describes one possible semantics ofIO a
IO
data IO a = Done a | PutChar Char (IO a) | GetChar (Char -> IO a)
IO
IO a
Done a
PutChar
GetChar
Char
GetChar
This tree contains all the information needed to execute teletype interactions.
One interprets (or executes) anIO a
PutChar
GetChar
Done
Done
main :: IO ()
()
This execution is not done anywhere in a haskell program, rather it is done by the run-time system.
The monadic operations are defined as follows:
return :: a -> IO a return x = Done x (>>=) :: IO a -> (a -> IO b) -> IO b Done x >>= f = f x PutChar c x >>= f = PutChar c (x >>= f) GetChar g >>= f = GetChar (\c -> g c >>= f)
return
Done
x
f
Done
x
f
Done
The primitive IO commands are defined using these constructors.
putChar :: Char -> IO () putChar x = PutChar x (Done ()) getChar :: IO Char getChar = GetChar (\c -> Done c)
putChar
IO ()
PutChar
Done
getChar
IO Char
GetChar
Done
Other teletype commands can be defined in terms of these primitives
putStr :: String -> IO () putStr = mapM_ putChar
IO a
IOTree
| SysCallName p1 p2 ... pn (r -> IO a)
p1
pn
r
PutChar
GetChar
IOTree
