2

I'm learning State Monad and cannot understand one example in Wiki (http://en.wikibooks.org/wiki/Haskell/Understanding_monads/State)

rollDie :: GeneratorState Int
rollDie = do generator <- get
             let (value, newGenerator) = randomR (1,6) generator
             put newGenerator
             return value

the put has definition

put newState = State $ \_ -> ((), newState)

It seems put just create a new State, what the real usage of this line? If want to use the value maybe should use <- to extract, and if want to use the state again should use get. It makes no difference if delete this line (or am i missing anything? ), So, what does this line really mean ?

2
  • You can think of State state a as a function, that, given a state state returns a new state and a value. put simply ignores the previous state, returns unit, but sets the given newState as state for the next computations.
    – Zeta
    Mar 19, 2015 at 9:52
  • @Zeta Thanks for reply! I understand what put do, but what's the put newGenerator usage here ? If I delete this line, does anything change ?
    – hliu
    Mar 19, 2015 at 9:56

1 Answer 1

7

Delete that put and get some random values. I predict you will always get the same "random value". That is how the random Generator in haskell works: It (i.e. randomR) is a pure function - given the same generator, it will always return the same result. You have to feed the newGenerator to the next call. This is done via put.

1
  • 3
    That's the reason a good State implementation provides state :: (s -> (a,s)) -> State s b. Then rollDie = state (randomR (1,6)).
    – Zeta
    Mar 19, 2015 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.