Question

This MonadState instance, copied from http://book.realworldhaskell.org/read/monad-transformers.html, gives me an error with GHC 7.4.2

instance (MonadState s m) => MonadState s (MaybeT m) where
  get = lift get
  put k = lift (put k)

gives

    Illegal instance declaration for `MonadState s (MaybeT m)'
  (All instance types must be of the form (T a1 ... an)
   where a1 ... an are *distinct type variables*,
   and each type variable appears at most once in the instance head.
   Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `MonadState s (MaybeT m)'

If I add XFlexibleInstances, I'm then told to add XUndecidableInstances instead - I don't think I should need these extensions here. How can get this instance to compile?

Was it helpful?

Solution

When you look at http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/src/Control-Monad-State-Class.html#MonadState, you see that it is also used in the "offical" implementation, so I guess it's needed. The comment says it has to do with the coverage condition, which is explained in these stackoverflow questions:

In this case, the variable s is not present on the right side, and the functonal dependency goes from right to left, so your instance is invalid. (Without UndecidableInstances)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top