The easiest way is to use the module System.Random
, it's in the random package, so you probably have to install it first.
This module defines to typeclasses:
class RandomGen g where
next :: g -> (Int,g)
-- ...
class Random r where
random :: RandomGen g => g -> (a,g)
randomR :: RandomGen g => (r,r) -> g -> (a, g)
The typeclass, you have to implement is Random, specific the first function (as the second makes no sense, you can just implement like randomR = const random
. What does random
? You get a random generator as input, you have to generate what you need for it, and give the new generator back.
To generate your random values, you could either use the State
monad, or something like this:
random g = (myResult,gn) where
(random1,g1) = next g
(random2,g2) = next g2
-- ...
You can then use the systems random generator by this function:
randomIO :: Random r => IO r
It is predefined and yields a different value each call.
However, finally you have to decide yourself how to define your Random instance.