comonad-random-0.1.2: 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

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 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 :: Copointed f => (f a -> f a) -> f a -> [a]Source

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