[Haskell-cafe] Newbie: State monad example questions

Dmitri O.Kondratiev dokondr at gmail.com
Mon May 19 17:04:39 EDT 2008

I am trying to understand State monad example15 at:

Example 15 uses getAny that I don't understand at all how it works:

getAny :: (Random a) => State StdGen a
getAny = do g      <- get
            (x,g') <- return $ random g
            put g'
            return x

1) random has type:
random :: (Random a, RandomGen g) => g -> (a, g)

and for State monad:

return a = State (\s -> (a, s))

return (random g) = State (\s -> ((a,g), s))

Is  it correct?

2) What x and g' will match to in:
       do ...
    (x,g') <- return $ random g

which, as I understand equals to:
       do ...
    (x,g') <- State (\s -> ((a,g), s))

What x and g' will match to in the last expression?

3) In general, in do expression (pseudo):
    do { x <- State (\s -> (a, s)); ...}

What x will refer to? Will x stand for a whole lambda function: \s -> (a, s)

4) How 'g <- get' works in this function (getAny) ?
5) Why we need 'put g'?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20080520/29d101ab/attachment-0001.htm

More information about the Haskell-Cafe mailing list