1

Given the following code

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

I know I can translate it as:

rollDie2 :: GeneratorState Int
rollDie2 = get >>= \generator ->let (value, newGenerator) = randomR(1,6) generator
                                in put newGenerator >> return value

I tested both functions with and without the put newGenerator >>, and they produce different results. My question is why? The put functions is pure, and the operator (>>) means that return value should be unaffected by prior results.

jberryman
  • 16,334
  • 5
  • 42
  • 83
hernan
  • 572
  • 4
  • 10
  • Your question as posted is difficult to understand. I'm not sure what you're asking. As an aside, your `rollDie` function can be rewritten `rollDie = state (randomR (1,6))` – cdk Jul 11 '13 at 16:30
  • Where is `GeneratorState` defined? Also, how did you "test" these functions? – mhwombat Jul 11 '13 at 16:34
  • I think I found your `GeneratorState` here: https://en.wikibooks.org/wiki/Haskell/Understanding_monads/State – mhwombat Jul 11 '13 at 16:44
  • 1
    My central question was about, why would exist a difference using or not the "put newGenerator>>". I write the two functions only to show my interpretation of the do notation. – hernan Jul 11 '13 at 19:30

1 Answers1

1

When I test both functions with the same initial state, I get the same answer:

λ> evalState rollDie (mkStdGen 0)
6
λ> evalState rollDie2 (mkStdGen 0)
6

I suspect you're not using the same state for both tests. How exactly are you testing the functions?

Here's an example where the state (i.e. the random number generator) gets modified:

test :: GeneratorState (Int, Int)
test = do
  a <- rollDie -- modifies the state!
  b <- rollDie2 -- gets a different state
  return (a, b)

runTest :: IO ()
runTest = do
  g <- getStdGen
  let (a, b) = evalState test g
  print a
  print b

As you can see, when you run this you get two different answers.

λ> runTest
4
2
mhwombat
  • 8,026
  • 28
  • 53