Safe Haskell | Safe-Inferred |
---|---|
Language | Haskell2010 |
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)
- data BatchT r m a
- type family Result req :: *
- type Handler req m = [req] -> m [Result req]
- request :: Applicative m => r -> BatchT r m (Result r)
- runBatchT :: (Monad tm, Monad m) => Handler r m -> (forall b. tm b -> m b) -> BatchT r tm a -> m a
- type Batch r = BatchT r Identity
- runBatch :: Monad m => Handler r m -> Batch r a -> m a
The monad
MonadTrans (BatchT r) | |
Monad m => Monad (BatchT r m) | |
Functor m => Functor (BatchT r m) | |
Applicative m => Applicative (BatchT r m) |
Usage
To use BatchT
effectively, you have to provide several things:
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
:: (Monad tm, Monad m) | |
=> Handler r m | function to handle requests |
-> (forall b. tm b -> m b) | function to run lifted |
-> 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.