monad-batch-0.1.0.0: A monad for batching requests together

Safe HaskellSafe-Inferred
LanguageHaskell2010

Control.Monad.Batch

Contents

Description

A data type for computations with requests that can be batched together and possibly executed more efficiently.

Inspired by Facebook's Haxl, but the implementation is pure (no IO).

Things to improve:

  • encode the first Handler law in the type (like the Cartesian Store Comonad from Multiplate paper)
  • support multiple response types (request type indexed by response type)

Synopsis

The monad

data BatchT r m a Source

The BatchT monad transformer.

Applicative combinator <*> will batch requests together.

Instances

Usage

To use BatchT effectively, you have to provide several things:

  • a request type req,
  • a response type Result req,
  • a handler function of type Handler req m, running in monad m.

type family Result req :: * Source

Mapping from request type to result type. You have to provide an instance for your request type.

type Handler req m = [req] -> m [Result req] Source

Handler function for batched requests. Functions handler :: Handler req m should satisfy the following laws:

pure (length xs) = length (handler xs)
pure handler (xs ++ ys) = liftA2 (++) (handler xs) (handler ys)

Making requests

The BatchT monad transformer adds one special operation to the underlying monad:

request :: Applicative m => r -> BatchT r m (Result r) Source

Introduce a request into the computation. When ran it will be passed to handler function for processing - possibly with other requests.

Running computations

runBatchT Source

Arguments

:: (Monad tm, Monad m) 
=> Handler r m

function to handle requests

-> (forall b. tm b -> m b)

function to run lifted tm actions in m

-> BatchT r tm a 
-> m a 

Run the computation.

The resulting monad doesn't have to be the same as transformed monad. Therefore a natural transformation from transformed monad to running monad must be provided.

Pure usage

type Batch r = BatchT r Identity Source

BatchT specialized to Identity monad.

runBatch :: Monad m => Handler r m -> Batch r a -> m a Source

Run a pure computation (in a monad).