mcandre
mcandre

Reputation: 24642

How do I generate random numbers in Haskell, using random-fu, with platform-agnostic code?

I can't figure out how to use Data.Random.Source.IO to generate random numbers in a multiplatform way.

I can generate random numbers in Unix using Data.Random.Source.DevRandom, and there is an example in the GitHub documentation for Windows using Data.Random.Source.MWC, but there is no example code for using Data.Random.Source.IO.

Upvotes: 4

Views: 1201

Answers (1)

Satvik
Satvik

Reputation: 11218

Ok I have converted the github example to use Source.IO

import Data.Random
import Data.Random.Source.IO


logNormal :: Double -> Double -> RVar Double
logNormal mu sigmaSq = do
    x <- normal mu sigmaSq
    return (exp x)

main = sample (logNormal 5 1) >>= print

You can see in the source of Data.Random.Source.IO that it just defines the suitable instance for MonadRandom IO.

You can generate a uniform random number from a list as

import Data.Random
import Data.Random.Source.IO

main = sample (randomElement [0..9]) >>= print

Upvotes: 4

Related Questions