无法推断(m~m1)

aba*_*aba 14 haskell

在GHC中编译此程序时:

import Control.Monad

f x = let
  g y = let
    h z = liftM not x
    in h 0
  in g 0
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

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
Run Code Online (Sandbox Code Playgroud)

为什么?此外,为f(f :: Monad m => m Bool -> m Bool)提供显式类型签名会使错误消失.但这与Haskell f根据错误消息自动推断的类型完全相同!

Jon*_*rdy 5

实际上,这非常简单.推断类型的let绑定变量被隐式推广到类型方案,所以你的方式有一个量词.广义类型h是:

h :: forall a m. (Monad m) => a -> m Bool
Run Code Online (Sandbox Code Playgroud)

而广义类型f是:

f :: forall m. (Monad m) => m Bool -> m Bool
Run Code Online (Sandbox Code Playgroud)

他们不一样m.如果你写这个,你会得到基本相同的错误:

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
Run Code Online (Sandbox Code Playgroud)

你可以通过启用"范围类型变量"扩展来修复它:

{-# 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
Run Code Online (Sandbox Code Playgroud)

或者通过let使用"单态本地绑定"扩展禁用-generalisation , MonoLocalBinds.

  • 这并不是那么简单,因为使用`ghc <= 7.6.1`时,即使使用显式的"NoMonoLocalBinds",问题也不会出现.行为改变了7.6.2,我不知道是故意还是偶然. (5认同)
  • 也许这是一个错误.在这种情况下,问题和答案是一个很好的repro案例和开始寻找的地方. (2认同)