Can't make a derived instance of MonadTrans for newtype - haskell

I have the following newtype declaration. It is wrapping a Monad stack transformer stacking some standard mtl monads like Reader and Except.
newtype TrxDbFileBased f a = TrxDbFileBased {
unTrxDbFileBased :: ExceptT TrxDbError (ReaderT TrxDbFileBasedEnv f) a
} deriving (
Functor
, Applicative
, Monad
, MonadError TrxDbError
, MonadReader TrxDbFileBasedEnv
, MonadIO
, MonadTrans
)
data TrxDbFileBasedEnv = TrxDbFileBasedEnv {
workingDirectory :: FilePath
} deriving (Show)
data TrxDbError = TrxDbErrorIO TrxDbFileBasedEnv IOException
| TrxDbErrorStr TrxDbFileBasedEnv String
deriving (Show)
I want this newtype to be an instance of MonadTrans but I am getting the following error.
• Can't make a derived instance of ‘MonadTrans TrxDbFileBased’
(even with cunning GeneralizedNewtypeDeriving):
cannot eta-reduce the representation type enough
• In the newtype declaration for ‘TrxDbFileBased’
|
31 | , MonadTrans
| ^^^^^^^^^^
I don't understand why MonadTrans cannot be derived given that the underlying type is ExceptT which is an instance of MonadTrans.

The problem is that, if this derivation worked, your instance of MonadTrans would be transforming the functor f, while the instance for ExceptT, which you're expecting to be used as base of derivation, is transforming monad ReaderT TrxDbFileBasedEnv f.
These are not representationally equivalent, so GeneralizedNewtypeDeriving can't help you here.
Here's another way to think about it: try implementing the class manually. If you try that, you'll see that your lift will have to be defined like this:
lift = TrxDbFileBased . lift . lift
that is, first lifting f into ReaderT, then lifting ReaderT into ExceptT, and then wrapping all of that in TrxDbFileBased. But GND expects to do nothing more than the no-op wrapping, which means just straight up reusing the method dictionary, since the types are representationally equivalent. This is not the case in your case.

Related

Haskell - MonadState

So I have recently been looking at state monads because I want to build a parser combinator library in haskell.
I came across a typeclass known as MonadState, I was wondering what is the point of this typeclass and where would you use it?
MonadState abstracts out the get and put functions so that they work not just for one type, but for any type that can act as a state monad. It's primarily to make monad transformers work.
Without going into too much detail, let's just assume you know that StateT exists: it takes one monad and returns a new monad that can act as state. (I'll ignore the difference between lazy and strict state monads here). A monad that handles state can then be defined by applying StateT to the Identity monad:
newtype State s = StateT s Identity
As long as the input type is a monad, we can provide a MonadState instance for the monad returned by StateT:
-- Add state to any monad
instance Monad m => MonadState s (StateT s m) where
...
This says that applying StateT to any monad (not just Identity) produces a monad that can be treated as a state monad.
Further, you can say that anything that wraps a state monad is also a state monad, as long as it implements MonadState:
-- Add Maybe to a state monad, it's still a state monad
instance MonadState s m => MonadState s (MaybeT m) where
...
-- Add Writer to a state monad, it's still a state monad
instance (Monoid w, MonadState s m) => MonadState s (WriterT w m) where
...
MonadState abstracts the state monad (as if this stuff wasn't abstract enough, right?). Instead of requiring a concrete type State with a Monad instance, it lets us use any Monad we like, provided we can provide appropriate get and put functions. In particular, we can use StateT which lets us combine effects.
simple example combining State and IO:
tick :: (MonadIO m, MonadState Int m) => m ()
tick = do
x <- get
liftIO $ putStrLn ("incrementing " ++ (show x))
put (x+1)
> runStateT (tick >> tick >> tick >> tick) 5
incrementing 5
incrementing 6
incrementing 7
incrementing 8
((),9)

Does Higher order polymorphism require strict order of arguments?

Reading LYAH, I stumbled upon this piece of code:
newtype Writer w a = Writer { runWriter :: (a, w) }
instance (Monoid w) => Monad (Writer w) where
return x = Writer (x, mempty)
(Writer (x,v)) >>= f = let (Writer (y, v')) = f x in Writer (y, v `mappend` v')
While trying to understand what the heck is Writer w in the first line, I discovered this not being a full type, but a sort of type constructor with 1 argument, like Maybe for Maybe String
Looks great, but what if the initial type if Writer' is defined with swapped type arguments, like this:
newtype Writer' a w = Writer' { runWriter :: (a, w) }
Is it possible to implement Monad instance now? Something like this, but what could actually be compiled:
instance (Monoid w) => Monad (\* -> Writer' * monoid) where
The idea of \* -> Writer' * monoid is the same as Writer w :
A type constructor with one type argument missing -- this time first one.
This is not possible in Haskell, what you'd need is a type-level lambda function, which does not exist.
There are type synonyms which you can use to define reorderings of type variables:
type Writer'' a w = Writer' a w
but you can not give class instances for partially applied type synonyms (even with the TypeSynonymInstances extension).
I wrote my MSc thesis about the subject of how type-level lambdas can be added to GHC: https://xnyhps.nl/~thijs/share/paper.pdf to be used in type-class instances without sacrificing type inference.
What you are seeing here is a parochial design choice of Haskell. It makes perfect sense, conceptually speaking, to say that your Writer' type is a functor if you "leave out" its first parameter. And a programming language syntax could be invented to allow such declarations.
The Haskell community hasn't done so, because what they have is relatively simple and it works well enough. This isn't to say that alternative designs aren't possible, but to be adopted such a design would have to:
Be no more complex to use in practice than what we already have;
Offer functionality or advantage that would be worth the switch.
This generalizes to many other ways that the Haskell community uses types; often the choice to represent something as a type distinction is tied to some artifact of the language's design. Many monad transformers are good examples, like MaybeT:
newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }
instance Functor m => Functor (MaybeT m) where ...
instance Applicative m => Applicative (MaybeT m) where ...
instance Monad m => Monad (MaybeT m) where ...
instance MonadTrans MaybeT where ...
Since it's a newtype, this means that MaybeT IO String is isomorphic to IO (Maybe String); you can think of the two types as being two "perspectives" on the same set of values:
IO (Maybe String) is an IO action that produces values of type Maybe String;
MaybeT IO String is a MaybeT IO action that produces values of type String.
The difference between the perspectives is that they imply different implementations of the Monad operations. In Haskell then this is also tied to the following parochial technical facts:
In one String is the last type parameter (the "values") and in the other Maybe String is;
IO and MaybeT IO have different instances for the Monad class.
But maybe there is a language design where you could say that the type IO (Maybe a) can have a monad specific to it, and distinct from the monad for the more general IO a type. That language would incur some complexity to make that distinction consistently (e.g., rules to determine which Monad instance to by default for IO (Maybe String) and rules to allow the programmer to override the default choice). And I'd wager modestly that the end result would be no less complex than what we do have. TL;DR: Meh.

Transformation under Transformers

I'm having a bit of difficulty with monad transformers at the moment. I'm defining a few different non-deterministic relations which make use of transformers. Unfortunately, I'm having trouble understanding how to translate cleanly from one effectful model to another.
Suppose these relations are "foo" and "bar". Suppose that "foo" relates As and Bs to Cs; suppose "bar" relates Bs and Cs to Ds. We will define "bar" in terms of "foo". To make matters more interesting, the computation of these relations will fail in different ways. (Since the bar relation depends on the foo relation, its failure cases are a superset.) I therefore give the following type definitions:
data FooFailure = FooFailure String
data BarFailure = BarSpecificFailure | BarFooFailure FooFailure
type FooM = ListT (EitherT FooFailure (Reader Context))
type BarM = ListT (EitherT BarFailure (Reader Context))
I would then expect to be able to write the relations with the following function signatures:
foo :: A -> B -> FooM C
bar :: B -> C -> BarM D
My problem is that, when writing the definition for "bar", I need to be able to receive errors from the "foo" relation and properly represent them in "bar" space. So I'd be fine with a function of the form
convert :: (e -> e') -> ListT (EitherT e (Reader Context) a
-> ListT (EitherT e' (Reader Context) a
I can even write that little beast by running the ListT, mapping on EitherT, and then reassembling the ListT (because it happens that m [a] can be converted to ListT m a). But this seems... messy.
There's a good reason I can't just run a transformer, do some stuff under it, and generically "put it back"; the transformer I ran might have effects and I can't magically undo them. But is there some way in which I can lift a function just far enough into a transformer stack to do some work for me so I don't have to write the convert function shown above?
I think convert is a good answer, and using Control.Monad.Morph and Control.Monad.Trans.Either it's (almost) really simple to write:
convert :: (Monad m, Functor m, MFunctor t)
=> (e -> e')
-> t (EitherT e m) b -> t (EitherT e' m) b
convert f = hoist (bimapEitherT f id)
the slight problem is that ListT isn't an instance of MFunctor. I think this is the author boycotting ListT because it doesn't follow the monad transformer laws though because it's easy to write a type-checking instance
instance MFunctor ListT where hoist nat (ListT mas) = ListT (nat mas)
Anyway, generally take a look at Control.Monad.Morph for dealing with natural transformations on (parts of) transformer stacks. I'd say that fits the definition of lifting a function "just enough" into a stack.

Anatomy of a monad transformer

I'm trying to learn monad transformers, based on the standard Haskell libraries (mtl? transformers? not sure which one came with my download of the Haskell platform - 7.4.1).
What I believe I've noticed is a common structure for each monad transformer definition:
base type ('Base')
Monad instance
transformer type ('BaseT')
Monad instance
MonadTrans instance
MonadIO instance
transformer class ('MonadBase')
some operations
instances for other 'BaseT's
So for example, for the Writer monad, there'd be:
a Writer datatype/newtype/type, with a Monad instance
a WriterT datatype/newtype/type, with Monad, MonadTrans, and MonadIO instances
a MonadWriter class, and instances of this class for StateT, ReaderT, IdentityT, ...
Is this how monad transformers are organized? Am I missing anything/do I have any incorrect details?
The motivation for this question is figuring out:
what the relationships and differences are between the "BaseT"s and the corresponding "MonadBase"s and "Base"s
whether all three are required
how MonadTrans is related and what its purpose is
mtl package doesn't implement monad transformers. At least WriterT is just reexported from transformers.
transformers package implements WriterT, which is a monad transformer itself. Writer is just an alias:
type Writer w = WriterT w Identity
Some libraries can implement Writer separately, but anyway it is just a special case of WriterT. (Identity is a trivial monad, it doesn't have any additional behavior.)
MonadTrans allows you to wrap underlying monad into the transformed one. You can live without it, but you will need to perform manual wrapping (see MonadTrans instance definition for WriterT for example how to do it). The only use case where you really need MonadTrans -- when you don't know actual type of transformer.
MonadWriter is a type class declared in mtl. It's methods (writer, pass, tell and listen) are the same as function for WriterT. It allows to wrap (automatically!) WriterT computation through stack of transformers, even if you don't know exact types (and even number!) of transformers in the stack.
So, WriterT is the only type which is "required".
For other monad transformers it is the same: BaseT is a transformer, Base is a monad without underlying monad and MonadBase is a type class -- class of all monads, that have BaseT somewhere in transformers stack.
ADDED:
You can find great explanation in RWH book
Here is a basic example:
import Control.Monad.Trans
import Control.Monad.Trans.Writer
import Control.Monad.Trans.Reader hiding (ask)
-- `ask` from transformers
-- ask :: Monad m => ReaderT r m r
import qualified Control.Monad.Trans.Reader as TransReader (ask)
-- `ask` from mtl
-- ask :: MonadReader r m => m r
import qualified Control.Monad.Reader as MtlReader (ask)
-- Our monad transformer stack:
-- It supports reading Int and writing String
type M m a = WriterT String (ReaderT Int m) a
-- Run our monad
runM :: Monad m => Int -> M m a -> m (a, String)
runM i action = runReaderT (runWriterT action) i
test :: Monad m => M m Int
test = do
tell "hello"
-- v <- TransReader.ask -- (I) will not compile
v1 <- lift TransReader.ask -- (II) ok
v2 <- MtlReader.ask -- (III) ok
return (v1 + v2)
main :: IO ()
main = runM 123 test >>= print
Note that (I) will be rejected by compiler (try it to see the error message!). But (II) compiles, thanks to MonadTrans ("explicit lifting"). Thanks to MonadReader, (III) works out of the box ("implicit lifting"). Please read RWH book for explanation how it works.
(In the example we import ask from two different modules, that is why we need qualified import. Usually you will use only one of them at a time.)
Also I didn't mean to specifically ask about Writer.
Not sure I understand... Reader, State and others use the same schema. Replace Writer with State and you will have an explanation for State.

Why aren't monad transformers constrained to yield monads?

In the MonadTrans class:
class MonadTrans t where
-- | Lift a computation from the argument monad to the constructed monad.
lift :: Monad m => m a -> t m a
why isn't t m constrained to be a Monad? i.e., why not:
{-# LANGUAGE MultiParamTypeClasses #-}
class Monad (t m) => MonadTrans t m where
lift :: Monad m => m a -> t m a
If the answer is "because that's just the way it is", that's fine -- it's just confusing for a n008.
You suggested the following:
class Monad (t m) => MonadTrans t m where
lift :: Monad m => m a -> t m a
...but does that really mean what you want? It seems you want to express something like "a type t may be an instance of MonadTrans if, for all m :: * -> * where m is an instance of Monad, t m is also an instance of Monad".
What the class definition above actually says is more like "types t and m may constitute an instance of MonadTrans if, for those specific types, t m is an instance of Monad". Consider carefully the difference, and the implied potential for instances that may not be what you'd want.
In the general case, every parameter of a type class is an independent "argument", a fact which has been a bountiful source of both headaches and GHC extensions as people have attempted to use MPTCs.
Which isn't to say that such a definition couldn't be used anyway--as you point out, the current definition is not ideal either. The age-old problem "Why Data.Set Is Not a Functor" is related, and such issues helped motivate the recent ConstraintKinds tomfoolery.
The ultimate answer to "why not" here is almost certainly the one given by Daniel Fischer in the comments--because MonadTrans is pretty core functionality, it would be undesirable to make it depend on some terrifying cascade of increasingly arcane GHC extensions.

Resources