Guess the number app does not work as expected

Viewed 140

The following piece of code should implement a simple guess the number game

import           Control.Monad (unless)
import           System.Random (Random (randomR), StdGen, getStdGen)

main :: IO ()
main = do
  gen <- getStdGen
  askForANumber gen

askForANumber :: StdGen -> IO ()
askForANumber gen = do
  let (randNumber, gen) = randomR (1, 10) gen :: (Int, StdGen)
  putStrLn "La ce numar intre 1 si 10 ma gandesc?"
  numberString <- getLine

  unless (null numberString) $ do
    let number = read numberString

    if randNumber == number
      then putStrLn "Ai ghicit!"
      else putStrLn $ "Imi pare rau era " ++ show randNumber

    askForANumber gen

The output is a surprising for me, but I am a beginner

enter image description here

If I replace line 7 with

askForANumber (mkStdGen 42)

All seems to work fine, so the problem seems to be getStdGen, what am I missing?

EDIT:

The mistake was on this line

  let (randNumber, gen) = randomR (1, 10) gen :: (Int, StdGen)

It used the gen recursively as @chi in comments pointed out

Replaced it with

  let (randNumber, newGen) = randomR (1, 10) gen :: (Int, StdGen)

And all works as expected.

0 Answers
Related