4

当我在 ghci 中定义这样的函数时:

> :m Control.Monad
> let f n = n+1
> let g = liftM f

他们运作良好:

> g $ Just 2
> Just 3
> g $ [1,2]
> [2,3]

但是当我在文件(probl.hs)中定义相同的函数时:

 import Control.Monad

 f :: Integer -> Integer
 f n = n + 2

 g = liftM f

然后通过 ghci 运行这个文件:

 ghci probl.hs

我收到这样的消息:

probl.hs:6:5: error:
    * Ambiguous type variable `m0' arising from a use of `liftM'
      prevents the constraint `(Monad m0)' from being solved.
      Relevant bindings include
        g :: m0 Integer -> m0 Integer (bound at probl.hs:6:1)
...
Failed, modules loaded: none.

为什么会有这样的区别?以及如何解决第二种情况的问题(我想要与第一种情况相同的行为)?

4

1 回答 1

3

你被可怕的单态限制击中了!这是一个不直观的规则,在 GHCi 中关闭,但在编译时打开。使用类型签名(推荐),或{-# LANGUAGE NoMonomorphismRestriction #-}禁用它。基本上,它有时会使没有类型签名的表达式的多态性低于您的预期。

进一步阅读

于 2017-04-06T12:46:32.350 回答