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
The following function generates an infinite list of dice throw
sums with n
dice.
rolls :: RandomGen g => Int -> g -> [Int] rolls n = extracts left . -- Extract an infinite list of the sums. fmap (sum . take n) . -- Sum the first n values of each list. extend (extracts next) . -- Group them into lists of die values. mkRandR (1,6) -- Generate random die values.
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.