[Haskell-cafe] Newbie: State monad example questions

Jules Bean jules at jellybean.co.uk
Wed May 21 10:54:52 EDT 2008


Dmitri O.Kondratiev wrote:
> Thanks everybody for your help!
> Oliver,  you provided an excellent write-up  on  State  monad without  
> going  into 'scary' :) details, great work indeed!
> Alas,  in this case I need the details, and in particular the most scary 
> ones!
> 
> So let's start with fundamental and most intriguing  (to me) things:
> 
> getAny :: (Random a) => State StdGen a
> getAny = do g <- get -- magically get the current StdGen
> 
> First line above declares a data type:
> 
> State StdGen a
> 
> which is constructed with the function:
> 
> State {runState :: (StdGen -> (a, StdGen))}
> 
> Q1: Where in the example 
> (http://www.haskell.org/all_about_monads/examples/example15.hs) data of 
> this type *actually gets constructed* ?

Actually get constructed?

It gets constructed by >>= and return, both of which construct state 
objects:

instance Monad (State s) where
     return a = State $ \s -> (a, s)
     m >>= k  = State $ \s -> let
         (a, s') = runState m s
         in runState (k a) s'


How do >>= and return get called? Well you can see explicit calls to 
return. The >>= is implicit in the way do-notation is desugared.

getAny = do g      <- get
             let (x,g') = random g
	    put g'
	    return x

rewrites to

getAny = get >>= \g -> ( let (x,g') = random g in (put g' >> return x) )

where I have added some not strictly necessary ()s and taken the liberty 
of changing the confusing "a <- return x" idiom to "let a = x".

So the *actually gets constructed* part is that use of >>= .

HTH,

Jules


More information about the Haskell-Cafe mailing list