monad-unlift-0.2.0/0000755000000000000000000000000012712033227012273 5ustar0000000000000000monad-unlift-0.2.0/ChangeLog.md0000644000000000000000000000016312712033227014444 0ustar0000000000000000## 0.2.0 * Split out monad-unlift-ref ## 0.1.1.0 * Add `MonadResource` instances ## 0.1.0.0 * Initial release monad-unlift-0.2.0/LICENSE0000644000000000000000000000204312712033227013277 0ustar0000000000000000Copyright (c) 2015 Michael Snoyman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. monad-unlift-0.2.0/monad-unlift.cabal0000644000000000000000000000163312712033227015657 0ustar0000000000000000name: monad-unlift version: 0.2.0 synopsis: Typeclasses for representing monad transformer unlifting description: See README.md homepage: https://github.com/fpco/monad-unlift license: MIT license-file: LICENSE author: Michael Snoyman maintainer: michael@fpcomplete.com copyright: FP Complete category: Control build-type: Simple extra-source-files: README.md ChangeLog.md cabal-version: >=1.10 library exposed-modules: Control.Monad.Trans.Unlift build-depends: base >= 4.6 && < 5 , monad-control >= 1.0 && < 1.1 , transformers , transformers-base , constraints default-language: Haskell2010 source-repository head type: git location: https://github.com/fpco/monad-unlift.git monad-unlift-0.2.0/README.md0000644000000000000000000002064412712033227013560 0ustar0000000000000000## monad-unlift [![Build Status](https://travis-ci.org/fpco/monad-unlift.svg?branch=master)](https://travis-ci.org/fpco/monad-unlift) Typeclasses for providing for unlifting of monad transformers and stacks. Note that concrete implementations of common transformers implementing these type classes are provided by the monad-unlift-ref package. ## Synopsis ```haskell import Control.Concurrent.Async import Control.Monad.Trans.Unlift import Control.Monad.Trans.RWS.Ref import Control.Monad.IO.Class import Data.Mutable -- Some artbirary data type for the MonadReader data SomeEnv = SomeEnv Int myFunc :: RWSRefT -- The WriterT piece is contained by an IORef IORef -- For efficiency, we store the state in a primitive reference (PRef RealWorld) SomeEnv -- Reader [String] -- Writer Int -- State IO (String, String) myFunc = do -- Get the unlift function. Due to weaknesses in ImpredicativeTypes, we -- need to use a newtype wrapper. You can also use askRunBase. -- -- If you want to just unwrap one transformer layer, use -- askUnlift/askRun/Unlift. UnliftBase run <- askUnliftBase -- Note that we can use unlift to turn our transformer actions into IO -- actions. Unlike the standard RWST, actions from separate threads are -- both retained due to mutable references. -- -- In real life: you shouldn't rely on this working, as RWST is not thread -- safe. This example is provided as a good demonstration of the type level -- functionality. liftIO $ concurrently (run foo) (run bar) where foo = do tell ["starting foo"] modify (+ 1) tell ["leaving foo"] return "foo is done" bar = do tell ["starting bar"] SomeEnv e <- ask modify (+ e) tell ["leaving bar"] return "bar is done" main :: IO () main = do ((w, x), y, z) <- runRWSRefT myFunc (SomeEnv 5) 6 print w -- foo is done print x -- bar is done print y -- 12 = 6 + 5 + 1 print z -- starting and leaving statements, order ambiguous ``` ## Overview A common pattern is to have some kind of a monad transformer, and want to pass an action into a function that requires actions in a base monad. That sounds a bit abstract, so let's give a concrete example: ```haskell -- From async concurrently :: IO a -> IO b -> IO (a, b) func1 :: ReaderT Foo IO String func2 :: ReaderT Foo IO Double doBoth :: ReaderT Foo IO (String, Double) doBoth = _ ``` Doing this manually is possible, but a bit tedious: ```haskell doBoth :: ReaderT Foo IO (String, Double) doBoth = ReaderT $ \foo -> concurrently (runReaderT func1 foo) (runReaderT func2 foo) ``` This also doesn't generalize at all; you'll be stuck writing `concurrently` variants for every monad transformer stack. Fortunately, the `monad-control` package generalizes this to a large number of transformer stacks. Let's implement our generalized `concurrently`: ```haskell concurrentlyG :: MonadBaseControl IO m => m a -> m b -> m (StM m a, StM m b) concurrentlyG f g = liftBaseWith $ \run -> concurrently (run f) (run g) ``` Notice how, in the signature for `concurrentlyG`, we no longer return `(a, b)`, but `(StM m a, StM m b)`. This is because there may be additional monadic context for each thread of execution, and we have no way of merging these together in general. Some examples of context are: * With `WriterT`, it's the values that you called `tell` on * With `EitherT`, the returned value may not exist at all In addition to this difficulty, many people find the types in `monad-control` difficult to navigate, due to their extreme generality (which is in fact the power of that package!). There is a subset of these transformer stacks that are in fact [monad morphisms](http://www.stackage.org/package/mmorph). Simply stated, these are transformer stacks that are isomorphic to `ReaderT`. For these monads, there is not context in the returned value. Therefore, there's no need to combine returned states or deal with possibly missing values. This concept is represented by the monad-unlift package, which provides a pair of typeclasses for these kinds of transformer stacks. Before we dive in, let's see how we solve our `concurrentlyG` problem with it: ```haskell concurrentlyG :: MonadBaseUnlift IO m => m a -> m b -> m (a, b) concurrentlyG f g = do UnliftBase run <- askUnliftBase liftBase $ concurrently (run f) (run g) ``` Notice how we get `(a, b)` in the return type as desired. There's no need to unwrap values or deal with context. ### MonadTransUnlift `MonadTransUnlift` is a class for any monad transformer which is isomorphic to `ReaderT`, in the sense that the environment can be captured and applied later. Some interesting cases in this space are: * `IdentityT` and things isomorphic to it; in this case, you can think of the environment as being `()` * Transformers which contain a mutable reference in their environment. This allows them to behave like stateful transformers (e.g., `StateT` or `WriterT`), but still obey the monad morphism laws. (See below for more details.) Due to weaknesses in GHC's ImpredicativeTypes, we have a helper datatype to allow for getting polymorphic unlift functions, appropriately named `Unlift`. For many common cases, you can get away with using `askRun` instead, e.g.: ```haskell bar :: ReaderT Foo IO () baz :: ReaderT Foo IO () baz = do run <- askRun liftIO $ void $ forkIO $ run bar ``` Using `Unlift`, this would instead be: ```haskell Unlift run <- askUnlift liftIO $ void $ forkIO $ run bar ``` or equivalently: ```haskell u <- askUnlift liftIO $ void $ forkIO $ unlift u bar ``` ### MonadBaseUnlift `MonadBaseUnlift` extends this concept to entire transformer stacks. This is typically the typeclass that people end up using. You can think of these two typeclasses in exactly the same way as `MonadTrans` and `MonadIO`, or more precisely `MonadTrans` and `MonadBase`. For the same ImpredicativeTypes reason, there's a helper type `UnliftBase`. Everything we just discussed should transfer directly to `MonadBaseUnlift`, so learning something new isn't necessary. For example, you can rewrite the last snippet as: ```haskell u <- askUnliftBase liftIO $ void $ forkIO $ unliftBase u bar ``` ### Reference transformers When playing transformer stack games with a transformer like `StateT`, it's common to accidentally discard state modifications. Additionally, in the case of runtime exceptions, it's usually impossible to retain the state. (Similar statements apply to `WriterT` and `RWST`, both in strict and lazy variants.) Another approach is to use a `ReaderT` and hold onto a mutable reference. This is problematic since there's no built in support for operations like `get`, `put`, or `tell`. What we want is to have a `MonadState` and/or `MonadWriter` instance. To address this case, this package includes variants of those transformers that use mutable references. These references are generic using the [mutable-containers](http://www.stackage.org/package/mutable-containers) package, which allows you to have highly efficient references like `PRef` instead of always using boxed references like `IORef`. Note that, for generality, the reference transformers take type parameters indicating which mutable reference type to use. Some examples you may use are: * `IORef` for boxed references in `IO` * `STRef s` for boxed references in `ST` * `PRef RealWorld` for an unboxed reference in `IO` See the synopsis for a complete example. ### conduit The `transPipe` function in conduit has caused confusion in the past due to its requirement of provided functions to obey monad morphism laws. This package makes a good companion to conduit to simplify that function's usage. ### Other notable instances Both the `HandlerT` transformer from yesod-core and `LoggingT`/`NoLoggingT` are valid monad morphisms. `HandlerT` is in fact my first example of using the "environment holding a mutable reference" technique to overcome exceptions destroying state. ```haskell {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} import Control.Concurrent.Async import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Trans.Unlift main :: IO () main = runStdoutLoggingT foo foo :: (MonadLogger m, MonadBaseUnlift IO m, MonadIO m) => m () foo = do run <- askRunBase a <- liftIO $ async $ run $ $logDebug "Hello World!" liftIO $ wait a ``` monad-unlift-0.2.0/Setup.hs0000644000000000000000000000005612712033227013730 0ustar0000000000000000import Distribution.Simple main = defaultMain monad-unlift-0.2.0/Control/0000755000000000000000000000000012712033227013713 5ustar0000000000000000monad-unlift-0.2.0/Control/Monad/0000755000000000000000000000000012712033227014751 5ustar0000000000000000monad-unlift-0.2.0/Control/Monad/Trans/0000755000000000000000000000000012712033227016040 5ustar0000000000000000monad-unlift-0.2.0/Control/Monad/Trans/Unlift.hs0000644000000000000000000001021112712033227017630 0ustar0000000000000000{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} #if __GLASGOW_HASKELL__ >= 800 {-# LANGUAGE UndecidableSuperClasses #-} #endif -- | See overview in the README.md module Control.Monad.Trans.Unlift ( -- * Trans MonadTransUnlift , Unlift (..) , askUnlift , askRun -- * Base , MonadBaseUnlift , UnliftBase (..) , askUnliftBase , askRunBase -- * Reexports , MonadTrans (..) , MonadBase (..) , MonadTransControl (..) , MonadBaseControl (..) ) where import Control.Monad (liftM) import Control.Monad.Base (MonadBase (..)) import Control.Monad.Trans.Class (MonadTrans (..)) import Control.Monad.Trans.Control (MonadBaseControl (..), MonadTransControl (..)) import Data.Constraint ((:-), (\\)) import Data.Constraint.Forall (Forall, inst) -- | A function which can move an action down the monad transformer stack, by -- providing any necessary environment to the action. -- -- Note that, if ImpredicativeTypes worked reliably, this type wouldn't be -- necessary, and 'askUnlift' would simply include a more generalized type. -- -- Since 0.1.0 newtype Unlift t = Unlift { unlift :: forall a n. Monad n => t n a -> n a } class (StT t a ~ a) => Identical t a instance (StT t a ~ a) => Identical t a -- | A monad transformer which can be unlifted, obeying the monad morphism laws. -- -- Since 0.1.0 class (MonadTransControl t, Forall (Identical t)) => MonadTransUnlift t instance (MonadTransControl t, Forall (Identical t)) => MonadTransUnlift t mkUnlift :: forall t m a . (Forall (Identical t), Monad m) => (forall n b. Monad n => t n b -> n (StT t b)) -> t m a -> m a mkUnlift r act = r act \\ (inst :: Forall (Identical t) :- Identical t a) -- | Get the 'Unlift' action for the current transformer layer. -- -- Since 0.1.0 askUnlift :: forall t m. (MonadTransUnlift t, Monad m) => t m (Unlift t) askUnlift = liftWith unlifter where unlifter :: (forall n b. Monad n => t n b -> n (StT t b)) -> m (Unlift t) unlifter r = return $ Unlift (mkUnlift r) -- | A simplified version of 'askUnlift' which addresses the common case where -- polymorphism isn't necessary. -- -- Since 0.1.0 askRun :: (MonadTransUnlift t, Monad (t m), Monad m) => t m (t m a -> m a) askRun = liftM unlift askUnlift {-# INLINE askRun #-} -- | Similar to 'Unlift', but instead of moving one layer down the stack, moves -- the action to the base monad. -- -- Since 0.1.0 newtype UnliftBase b m = UnliftBase { unliftBase :: forall a. m a -> b a } class (StM m a ~ a) => IdenticalBase m a instance (StM m a ~ a) => IdenticalBase m a -- | A monad transformer stack which can be unlifted, obeying the monad morphism laws. -- -- Since 0.1.0 class (MonadBaseControl b m, Forall (IdenticalBase m)) => MonadBaseUnlift b m | m -> b instance (MonadBaseControl b m, Forall (IdenticalBase m)) => MonadBaseUnlift b m mkUnliftBase :: forall m a b. (Forall (IdenticalBase m), Monad b) => (forall c. m c -> b (StM m c)) -> m a -> b a mkUnliftBase r act = r act \\ (inst :: Forall (IdenticalBase m) :- IdenticalBase m a) -- | Get the 'UnliftBase' action for the current transformer stack. -- -- Since 0.1.0 askUnliftBase :: forall b m. (MonadBaseUnlift b m) => m (UnliftBase b m) askUnliftBase = liftBaseWith unlifter where unlifter :: (forall c. m c -> b (StM m c)) -> b (UnliftBase b m) unlifter r = return $ UnliftBase (mkUnliftBase r) -- | A simplified version of 'askUnliftBase' which addresses the common case -- where polymorphism isn't necessary. -- -- Since 0.1.0 askRunBase :: (MonadBaseUnlift b m) => m (m a -> b a) askRunBase = liftM unliftBase askUnliftBase {-# INLINE askRunBase #-}