Personal tools

Simple StateT use

From HaskellWiki

Revision as of 01:51, 13 November 2006 by DonStewart (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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 = runStateT code [1..] >> return ()
 
--
-- layer a infinite list of uniques over the IO monad
--
code = do
    x <- pop
    io $ print x
    y <- pop
    io $ print y
    return ()
 
--
-- pop the next unique off the stack
--
pop = do
    (x:xs) <- get
    put xs
    return x
 
io = liftIO