Random Numbers in Haskell

Haskell’s System.Random module provides pseudorandom number generation.

import System.Random

main :: IO ()
main = do
    -- For example, `randomRIO` returns a random Int n, 0 <= n < 100.
    n1 <- randomRIO (0, 99)
    n2 <- randomRIO (0, 99)
    putStrLn $ show n1 ++ "," ++ show n2

    -- `randomIO` returns a random Float f, 0.0 <= f < 1.0.
    f <- randomIO :: IO Float
    print f

    -- This can be used to generate random floats in other ranges, 
    -- for example 5.0 <= f' < 10.0.
    f1 <- randomRIO (5.0, 10.0)
    f2 <- randomRIO (5.0, 10.0)
    putStrLn $ show f1 ++ "," ++ show f2

    -- If you want a known seed, use `mkStdGen` to create a new
    -- StdGen (Standard Generator) and pass it to `randomRs`.
    let gen = mkStdGen 42
        (n3:n4:_) = take 2 $ randomRs (0, 99) gen
    putStrLn $ show n3 ++ "," ++ show n4

    -- Using the same seed will produce the same sequence of random numbers.
    let gen2 = mkStdGen 42
        (n5:n6:_) = take 2 $ randomRs (0, 99) gen2
    putStrLn $ show n5 ++ "," ++ show n6

To run the program, save it as random-numbers.hs and use runhaskell:

$ runhaskell random-numbers.hs
68,56
0.8090228
5.840125,6.937056
94,49
94,49

Some of the generated numbers may be different when you run the sample.

See the System.Random module documentation for references on other random quantities that Haskell can provide.

In Haskell, we use the System.Random module for random number generation. The randomRIO function is used to generate random numbers within a specified range, similar to rand.IntN in Go. For floating-point numbers, we use randomIO and randomRIO with appropriate type annotations.

To create a generator with a known seed, we use mkStdGen instead of NewPCG. The randomRs function is then used to generate a list of random numbers from this generator.

Note that Haskell’s random number generation is pure, meaning that for a given seed, it will always produce the same sequence of random numbers. This is why we get the same output when using the same seed twice.