comonad-random-0.1.0: Comonadic interface for random values

Control.Comonad.Random

Contents

Description

This module provides a comonadic interface to random values. In some situations, this may be more natural than a monadic approach.

Synopsis

Documentation

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 Rands for longer than necessary.

Data Type

data Rand a Source

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.

Transformations

next :: Rand a -> Rand aSource

Get the generator for the next value.

left :: Rand a -> Rand aSource

Split the generator, returning the new left one.

right :: Rand a -> Rand aSource

Split the generator, returning the new right one.

Convenience

extracts :: (Rand a -> Rand a) -> Rand a -> [a]Source

Generate an infinite list of values by applying a function repeatedly.