This module provides a comonadic interface to random values. In some situations, this may be more natural than a monadic approach.
Documentation
module Control.Comonad
module System.Random
Example
This example is based on the example given in the MonadRandom package.
rolls
is a supply of random dice rolls, picking a number between
1 and 6, inclusive.
rolls :: RandomGen g => g -> Rand Int rolls = mkRandR (1, 6)
extractN
may be used to supply n
values from a Rand
.
extractN :: Int -> Rand a -> [a] extractN n = take n . extracts next
We can bootstrap the whole thing with a generator, giving us a pure interface to the random values.
main = print . extractN 2 . rolls =<< getStdGen
One potential gotcha with this library is that a top-level Rand
that is extracted deeply could result in a space leak due to the
memoization. It's a good idea to try not to hold on to Rand
s for
longer than necessary.
Data Type
A memoized supply of values
Creation
mkRand :: (RandomGen g, Random a) => g -> Rand aSource
Create a comonadic generator from a RandomGen
.
mkRandR :: (RandomGen g, Random a) => (a, a) -> g -> Rand aSource
Create a comonadic generator from a RandomGen
where the values
are limited to a given range.