[Haskell-cafe] Beginner: IORef constructor?

Donald Bruce Stewart dons at cse.unsw.edu.au
Fri Dec 1 03:30:14 EST 2006


tjay.dreaming:
> Thanks. I've been reading the docs and examples on State (in
> Control.Monad.State), but I can't understand it at all. ticks and
> plusOnes... All they seem to do is return their argument plus 1...

Here's a little demo. (I agree, the State docs could have nicer demos)

Play around with the code, read the haddocks, and it should make sense
eventually :)_

-- Don


    import Control.Monad.State

    --
    -- the type for a 'global' 'variable'
    --
    data T = T { ref :: Int }

    -- Run code with a single global 'ref', initialised to 0
    main = evalStateT g $ T { ref = 0 }

    -- set it to 10
    g = do
        printio "g"
        putRef 10
        printio "modified state"
        f

    -- read that ref, print it
    f = do
        r <- getRef
        printio r
        return ()

    getRef = gets ref

    putRef x = modify $ \_ -> T { ref = x }

    printio :: Show a => a -> StateT T IO ()
    printio = liftIO . print


More information about the Haskell-Cafe mailing list