[Haskell-cafe] Newbie: State monad example questions

Dmitri O.Kondratiev dokondr at gmail.com
Wed May 21 11:22:46 EDT 2008


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 <jules at jellybean.co.uk> wrote:

> 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 at gmail.com
http://www.geocities.com/dkondr
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20080521/811ef2d5/attachment.htm


More information about the Haskell-Cafe mailing list