IO Semantics
From HaskellWiki
(Difference between revisions)
m |
m (Replaced "to" with "is") |
||
| Line 4: | Line 4: | ||
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. | ||
| - | The idea | + | The idea is to define <hask>IO</hask> as |
<haskell> | <haskell> | ||
newtype IO a = IO {runIO :: (a -> IOTree) -> IOTree} | newtype IO a = IO {runIO :: (a -> IOTree) -> IOTree} | ||
Revision as of 21:56, 24 July 2008
Semantics of IO: A Continuation Approach
The following is inspired by Luke Palmer's post. This only describes one possible semantics ofIO a
IO
newtype IO a = IO {runIO :: (a -> IOTree) -> IOTree}
IO
Cont IOTree
IO
Cont
return x = IO (\k -> k x) x >>= f = IO (\k -> runIO x (\a -> runIO (f a) k))
IOTree
IOTree
data IOTree = Done | PutChar Char IOTree | GetChar (Char -> IOTree)
GetChar
IOTree
IOTree
PutChar
GetChar
Done
The primitive IO commands are defined using these constructors.
putChar :: Char -> IO () putChar x = IO (\k -> PutChar x (k ())) getChar :: IO Char getChar = IO (\k -> GetChar (\x -> k x))
PutChar
| PutChar Char (() -> IOTree)
Then the primitive IO commands could be defined directly in terms of these constructors:
putChar :: Char -> IO () putChar = IO . PutChar getChar :: IO Char getChar = IO GetChar
Other teletype commands can be defined in terms of these primitives
putStr :: String -> IO () putStr = mapM_ putChar
IOTree
IOTree
| SysCallName p1 p2 ... pn (r -> IOTree)
p1
pn
r
PutChar
GetChar
IOTree
IOTree
IO ()
(() -> IOTree) -> IOTree
IOTree -> IOTree
IOTree
runIO main (\() -> Done) :: IOTree
\() -> Done
main
main
IO a
IO (\k -> filterTree (not . isPutChar) (k ())) :: IO ()
putChar
