Generate a random integer in a range in Haskell without a seed

前端 未结 5 1305
自闭症患者
自闭症患者 2020-12-14 08:52

How can I generate a random number in Haskell from a range (a, b) without using any seed?

The function should return an Int and not an IO Int. I have a function X t

5条回答
  •  半阙折子戏
    2020-12-14 09:04

    A function cannot return an Int without IO, unless it is a pure function, i.e. given the same input you will always get the same output. This means that if you want a random number without IO, you will need to take a seed as an argument.

    Using the random library:

    • If you choose to take a seed, it should be of type StdGen, and you can use randomR to generate a number from it. Use newStdGen to create a new seed (this will have to be done in IO).

       > import System.Random
       > g <- newStdGen
       > randomR (1, 10) g
       (1,1012529354 2147442707)
      

      The result of randomR is a tuple where the first element is the random value, and the second is a new seed to use for generating more values.

    • Otherwise, you can use randomRIO to get a random number directly in the IO monad, with all the StdGen stuff taken care of for you:

       > import System.Random
       > randomRIO (1, 10)
       6
      

提交回复
热议问题