gpt4 book ai didi

haskell - ghci 中的 liftM : why is there such difference?

转载 作者:行者123 更新时间:2023-12-02 18:23:26 28 4
gpt4 key购买 nike

当我在 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 #-} 禁用它。基本上,它有时会使没有类型签名的表达式的多态性低于您的预期。

Further reading

关于haskell - ghci 中的 liftM : why is there such difference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43255051/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com