首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法推导(m ~ m1)

无法推导(m ~ m1)
EN

Stack Overflow用户
提问于 2013-07-21 03:04:56
回答 1查看 1.4K关注 0票数 14

在GHC中编译此程序时:

代码语言:javascript
运行
复制
import Control.Monad

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

我收到一个错误:

代码语言:javascript
运行
复制
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

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

EN

回答 1

Stack Overflow用户

发布于 2013-07-21 04:07:10

实际上,这非常简单。推断出的let-bound变量类型被隐式地泛化为类型方案,因此在您的方式中有一个量词。h的一般类型是:

代码语言:javascript
运行
复制
h :: forall a m. (Monad m) => a -> m Bool

f的一般类型是:

代码语言:javascript
运行
复制
f :: forall m. (Monad m) => m Bool -> m Bool

它们不是同一个m。如果你写了下面的代码,你基本上会得到同样的错误:

代码语言:javascript
运行
复制
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

您可以通过启用“作用域类型变量”扩展来修复它:

代码语言:javascript
运行
复制
{-# 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

或者使用“单态本地绑定”扩展MonoLocalBinds禁用let-generalisation。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17765690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档