Personal tools

Simple StateT use

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
(document StateT example)
 
m (Added type signatures)
Line 7: Line 7:
 
import Control.Monad.State
 
import Control.Monad.State
   
  +
main :: IO ()
 
main = runStateT code [1..] >> return ()
 
main = runStateT code [1..] >> return ()
 
 
--
 
--
 
-- layer a infinite list of uniques over the IO monad
 
-- layer a infinite list of uniques over the IO monad
 
--
 
--
  +
  +
code :: StateT [Integer] IO ()
 
code = do
 
code = do
 
x <- pop
 
x <- pop
Line 22: Line 24:
 
-- pop the next unique off the stack
 
-- pop the next unique off the stack
 
--
 
--
  +
pop :: StateT [Integer] IO Integer
 
pop = do
 
pop = do
 
(x:xs) <- get
 
(x:xs) <- get
Line 27: Line 30:
 
return x
 
return x
   
  +
io :: IO a -> StateT [Integer] IO a
 
io = liftIO
 
io = liftIO
 
</haskell>
 
</haskell>

Revision as of 04:35, 11 February 2007

A small example showing how to combine a State monad (in this case a unique supply), with the IO monad, via a monad transformer.

No need to resort to nasty mutable variables or globals!

import Control.Monad.State
 
main :: IO ()
main = runStateT code [1..] >> return ()
--
-- layer a infinite list of uniques over the IO monad
--
 
code :: StateT [Integer] IO ()
code = do
    x <- pop
    io $ print x
    y <- pop
    io $ print y
    return ()
 
--
-- pop the next unique off the stack
--
pop :: StateT [Integer] IO Integer
pop = do
    (x:xs) <- get
    put xs
    return x
 
io :: IO a -> StateT [Integer] IO a
io = liftIO