[Haskell-cafe] Newbie: State monad example questions
Thomas Hartman
tphyahoo at gmail.com
Wed May 21 04:11:36 EDT 2008
I would be interested in seeing good motivating examples for use of
the state monad, other than that example from All About Monads.
Okay, it's good for randomness. What else?
Reading the source code for State, I think I saw an example about
using state to uniquely label elements of a tree with ascending
integers, such that equal leaves in the original tree are also equal
in the int-labeled tree. But this struck me as something that could be
more elegantly done with some kind of tree fold.
So, are there any other simple motivating examples that show what
state is really good for?
Thomas.
Am 19. Mai 2008 16:04 schrieb Dmitri O.Kondratiev <dokondr at gmail.com>:
> I am trying to understand State monad example15 at:
> http://www.haskell.org/all_about_monads/html/statemonad.html
>
> 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
>
>
> Questions:
> 1) random has type:
> random :: (Random a, RandomGen g) => g -> (a, g)
>
> and for State monad:
>
> return a = State (\s -> (a, s))
>
> then:
> 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'?
>
> Thanks!
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
More information about the Haskell-Cafe
mailing list