
Jules,
Stupid question, please bear with me:
x :: Int -- x declared, but not constructed
x = 1 -- x constructed
s1 :: State StdGen a -- s1 declared, yes, but why s1 is *also already
constructed* ?
On Wed, May 21, 2008 at 6:54 PM, Jules Bean
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
-- Dmitri O. Kondratiev dokondr@gmail.com http://www.geocities.com/dkondr