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!
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With