Jules,<br><br>Stupid question, please bear with me:<br><br>x :: Int -- x declared, but not constructed<br>x = 1 -- x constructed<br><br>s1 ::
State StdGen a -- s1 declared, yes, but why s1 is *also already constructed* ?<br><br><div class="gmail_quote">On Wed, May 21, 2008 at 6:54 PM, Jules Bean <<a href="mailto:jules@jellybean.co.uk">jules@jellybean.co.uk</a>> wrote:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;"><div class="Ih2E3d">Dmitri O.Kondratiev wrote:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Thanks everybody for your help!<br>
Oliver, you provided an excellent write-up on State monad without going into 'scary' :) details, great work indeed!<br>
Alas, in this case I need the details, and in particular the most scary ones!<br>
<br>
So let's start with fundamental and most intriguing (to me) things:<br>
<br>
getAny :: (Random a) => State StdGen a<br>
getAny = do g <- get -- magically get the current StdGen<br>
<br>
First line above declares a data type:<br>
<br>
State StdGen a<br>
<br>
which is constructed with the function:<br>
<br>
State {runState :: (StdGen -> (a, StdGen))}<br>
<br>
Q1: Where in the example (<a href="http://www.haskell.org/all_about_monads/examples/example15.hs" target="_blank">http://www.haskell.org/all_about_monads/examples/example15.hs</a>) data of this type *actually gets constructed* ?<br>
</blockquote>
<br></div>
Actually get constructed?<br>
<br>
It gets constructed by >>= and return, both of which construct state objects:<br>
<br>
instance Monad (State s) where<div class="Ih2E3d"><br>
return a = State $ \s -> (a, s)<br></div>
m >>= k = State $ \s -> let<br>
(a, s') = runState m s<br>
in runState (k a) s'<br>
<br>
<br>
How do >>= and return get called? Well you can see explicit calls to return. The >>= is implicit in the way do-notation is desugared.<br>
<br>
getAny = do g <- get<div class="Ih2E3d"><br>
let (x,g') = random g<br>
put g'<br></div>
return x<br>
<br>
rewrites to<br>
<br>
getAny = get >>= \g -> ( let (x,g') = random g in (put g' >> return x) )<br>
<br>
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".<br>
<br>
So the *actually gets constructed* part is that use of >>= .<br>
<br>
HTH,<br><font color="#888888">
<br>
Jules<br>
</font></blockquote></div><br><br clear="all"><br>-- <br>Dmitri O. Kondratiev<br><a href="mailto:dokondr@gmail.com">dokondr@gmail.com</a><br><a href="http://www.geocities.com/dkondr">http://www.geocities.com/dkondr</a>