title: Type constraints for polymorphic functions like lift
body: <p>So I have this code</p>
  
  <pre><code>{-# LANGUAGE GeneralizedNewtypeDeriving #-}
  
  import MonadA
  
  data A = A
  
  newtype MonadA a =&gt; MyStateT a b { runMyStateT :: StateT A a b }
      deriving (Functor, Applicative, Monad, MonadIO, MonadState A)
  
  instance MonadTrans MyStateT where
      lift = MyStateT . lift
  </code></pre>
  
  <p>and I get the compiler complaining that it cannot prove the <code>m</code> from signature of <code>lift</code> is of type <code>MonadA</code> or thats how I read these cryptic error messages.</p>
  
  <pre><code>Could not deduce (MonadA m) arising from a use of `MyStateT'
  from the context (Monad m)
    bound by the type signature for
               lift :: Monad m =&gt; m a -&gt; MyStateT m a
  </code></pre>
  
  <p>is there a way to deal with this? I think I need the constraint to be able to instantiate as follows:</p>
  
  <pre><code>instance MonadA a =&gt; MonadA (MyStateT a) where
      f = MyStateT . lift . f
  </code></pre>
  
  <p>Also would such an implementation of <code>f</code> work? (I did not get that far due to the above error). I hope <code>f</code> on the right side to resolve to <code>f</code> over the inner monad <code>a</code>.</p>
  
  <hr>
  
  <p><strong>Edit</strong>: It indeed helped to drop the type constraint in <code>newtype MonadA a =&gt; MyStateT ...</code> to avoid the exact error that I mentioned. However there was just another error which I previously attributed to the same thing, consider this continuation of the example code above (some parts are repeated, now without type constraints):</p>
  
  <pre><code>class MonadB m where
      fB :: m ()
  
  newtype MyStateT m a = MyStateT { runMyStateT :: StateT A m a}
      deriving (... MonadState A ...)
  
  instance MonadTrans MyStateT where
      lift = MyStateT . lift
  
  instance MonadA a =&gt; MonadA (MyStateT a) where
      f = lift . f
  
  instance MonadA a =&gt; MonadB (MyStateT a) where
      fB = lift (modify (...))
  </code></pre>
  
  <p>the error is</p>
  
  <pre><code>Could not deduce (a ~ StateT A m0) from context (MonadA (MyStateT a), MonadA a)
  </code></pre>
  
  <p>in the implementation of <code>fB</code>. Earlier I tried <code>class MonadA m =&gt; MonadB m</code> to no avail. It doesn't even make sense to be matching <code>a</code> with <code>StateT A m</code>. Since <code>MyStateT</code> is an instance of <code>MonadState A</code> it should work, no?</p>
  
  <p><strong>Edit</strong>:</p>
  
  <p>OK, got it working:</p>
  
  <pre><code>fB = MyStateT (modify ...)
  </code></pre>
  
  <p>stupid me.</p>