Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not deduce (m ~ m1)

Tags:

haskell

When compiling this program in GHC:

import Control.Monad

f x = let
  g y = let
    h z = liftM not x
    in h 0
  in g 0

I receive an error:

test.hs:5:21:
    Could not deduce (m ~ m1)
    from the context (Monad m)
      bound by the inferred type of f :: Monad m => m Bool -> m Bool
      at test.hs:(3,1)-(7,8)
    or from (m Bool ~ m1 Bool, Monad m1)
      bound by the inferred type of
               h :: (m Bool ~ m1 Bool, Monad m1) => t1 -> m1 Bool
      at test.hs:5:5-21
      `m' is a rigid type variable bound by
          the inferred type of f :: Monad m => m Bool -> m Bool
          at test.hs:3:1
      `m1' is a rigid type variable bound by
           the inferred type of
           h :: (m Bool ~ m1 Bool, Monad m1) => t1 -> m1 Bool
           at test.hs:5:5
    Expected type: m1 Bool
      Actual type: m Bool
    In the second argument of `liftM', namely `x'
    In the expression: liftM not x
    In an equation for `h': h z = liftM not x

Why? Also, providing an explicit type signature for f (f :: Monad m => m Bool -> m Bool) makes the error disappear. But this is exactly the same type as the type that Haskell infers for f automatically, according to the error message!

like image 586
abacabadabacaba Avatar asked Jul 20 '13 19:07

abacabadabacaba


1 Answers

This is pretty straightforward, actually. The inferred types of let-bound variables are implicitly generalised to type schemes, so there’s a quantifier in your way. The generalised type of h is:

h :: forall a m. (Monad m) => a -> m Bool

And the generalised type of f is:

f :: forall m. (Monad m) => m Bool -> m Bool

They’re not the same m. You would get essentially the same error if you wrote this:

f :: (Monad m) => m Bool -> m Bool
f x = let
  g y = let
    h :: (Monad m) => a -> m Bool
    h z = liftM not x
    in h 0
  in g 0

And you could fix it by enabling the “scoped type variables” extension:

{-# LANGUAGE ScopedTypeVariables #-}

f :: forall m. (Monad m) => m Bool -> m Bool
f x = let
  g y = let
    h :: a -> m Bool
    h z = liftM not x
    in h 0
  in g 0

Or by disabling let-generalisation with the “monomorphic local bindings” extension, MonoLocalBinds.

like image 113
Jon Purdy Avatar answered Sep 20 '22 14:09

Jon Purdy