{-# LANGUAGE PolyKinds #-}
module Barbies.Internal.MonadT
( MonadT(..)
)
where
import Barbies.Internal.FunctorT(FunctorT(..))
import Control.Applicative (Alternative(..))
import Control.Applicative.Lift as Lift (Lift(..))
import Control.Applicative.Backwards as Backwards (Backwards(..))
import Control.Monad (join)
import Control.Monad.Trans.Identity(IdentityT(..))
import Control.Monad.Trans.Reader(ReaderT(..))
import Data.Coerce (coerce)
import Data.Functor.Compose (Compose(..))
import Data.Functor.Reverse (Reverse(..))
import Data.Functor.Product (Product(..))
import Data.Functor.Sum (Sum(..))
class FunctorT t => MonadT t where
tlift :: f a -> t f a
tjoin :: t (t f) a -> t f a
tjoin
= tembed id
tembed :: MonadT t => (forall x. f x -> t g x) -> t f a -> t g a
tembed h
= tjoin . tmap h
{-# MINIMAL tlift, tjoin | tlift, tembed #-}
instance Monad f => MonadT (Compose f) where
tlift = Compose . pure
{-# INLINE tlift #-}
tjoin (Compose ffga)
= Compose (join $ coerce <$> ffga)
{-# INLINE tjoin #-}
instance Alternative f => MonadT (Product f) where
tlift = Pair empty
{-# INLINE tlift #-}
tjoin (Pair fa (Pair fa' ga))
= Pair (fa <|> fa') ga
{-# INLINE tjoin #-}
instance MonadT (Sum f) where
tlift = InR
{-# INLINE tlift #-}
tjoin = \case
InL fa -> InL fa
InR (InL fa) -> InL fa
InR (InR ga) -> InR ga
instance MonadT Backwards where
tlift = Backwards
{-# INLINE tlift #-}
tjoin = coerce
{-# INLINE tjoin #-}
instance MonadT Lift where
tlift = Lift.Other
{-# INLINE tlift #-}
tjoin = \case
Lift.Pure a
-> Lift.Pure a
Lift.Other (Lift.Pure a)
-> Lift.Pure a
Lift.Other (Lift.Other fa)
-> Lift.Other fa
{-# INLINE tjoin #-}
instance MonadT IdentityT where
tlift = coerce
{-# INLINE tlift #-}
tjoin = coerce
{-# INLINE tjoin #-}
instance MonadT (ReaderT r) where
tlift = ReaderT . const
{-# INLINE tlift #-}
tjoin rra
= ReaderT $ \e -> coerce rra e e
{-# INLINE tjoin #-}
instance MonadT Reverse where
tlift = coerce
{-# INLINE tlift #-}
tjoin = coerce
{-# INLINE tjoin #-}