Randomness with Haskell
Following the CIS-194 course I stombled across the exercice 4 in homework 7:
type Rnd a = Rand StdGen a randomVec :: Random a => Int -> Rnd (Vector a)
Implement the function renadomVec so that it returns a random monad of a vector of the given length.
A quick check in ghci shows us all instances of Random:
class Random a where randomR :: RandomGen g => (a, a) -> g -> (a, g) random :: RandomGen g => g -> (a, g) randomRs :: RandomGen g => (a, a) -> g -> [a] randoms :: RandomGen g => g -> [a] randomRIO :: (a, a) -> IO a randomIO :: IO a -- Defined in `System.Random' instance Random Word -- Defined in `System.Random' instance Random Integer -- Defined in `System.Random' instance Random Int -- Defined in `System.Random' instance Random Float -- Defined in `System.Random' instance Random Double -- Defined in `System.Random' instance Random Char -- Defined in `System.Random' instance Random Bool -- Defined in `System.Random'
So we might get back a vector of these types packed in the random monad. The class MonadRandom defines some handy functions such as this one:
getRandoms :: Random a => m [a]
The only instance of MonadRandom is “RandT g m“ and Rand g is dfined as
type Rand g = RandT g Identity
So using the getRandom functions we get back a value of type Rnd a.
getRandoms returns an infinite stream of random values of type a. So a solution might look like this:
randomVec :: Random a => Int -> Rnd (Vector a) randomVec i = do rs <- getRandoms return $ V.fromList $ take i rs
rs is an infinite list of values of type a, but we just need i of them -> use the take function. And finally just convert the list to a vector.
The type of a is bound once we use the function, not earlier. So, using the function in ghci:
>evalRandIO $ (randomVec 2 :: Rand StdGen (Vector Int)) [-3465376240042775641,-3862684656236907452] >evalRandIO $ (randomVec 2 :: Rand StdGen (Vector Float)) [0.14833772,0.3634181] >evalRandIO $ (randomVec 2 :: Rand StdGen (Vector Bool)) [True,False]
Further information you may get from this SO post.













