ghci中的liftM:为什么会有这样的差异



当我在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.

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

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

延伸阅读

最新更新