Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

random

haskell

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 that takes and Int and other arguments and outputs something which is not an IO.

If this is not possible, how can I generate a seed using the Time library and the generate a random number in the range with the mkStdGen ?

Any help would be really appreciated.


1 Answers

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
    
like image 120
hammar Avatar answered Sep 14 '25 10:09

hammar