2016-04-15 25 views
1

我注意到我写的一个函数现在不起作用,尽管在其他场合成功使用它。没有使用'next'的实例

我的测试文件(做一个只是为了测试这个问题)看起来是这样的:

import System.Random 
generator = next . snd 

这将导致错误

No instance for (RandomGen g0) arising from a use of ‘next’ 
The type variable ‘g0’ is ambiguous 
Relevant bindings include 
    generator :: (a, g0) -> (Int, g0) (bound at Test.hs:2:1) 
Note: there is a potential instance available: 
    instance RandomGen StdGen -- Defined in ‘System.Random’ 
In the first argument of ‘(.)’, namely ‘next’ 
In the expression: next . snd 
In an equation for ‘generator’: generator = next . snd 

奇怪的是,如果我打开ghci中和类型:

import System.Random 
let generator = next . snd 

一切正常。我错过了什么?

编辑:也尝试这样做,它工作得很好:

generator something = next (snd something) 
+3

ahhh您找到[Monomorphism Restriction Instance](https://wiki.haskell.org/Monomorphism_restriction);) - 在GHCi中运行':set -XMonomorphismRestriction',您将得到相同的结果 – Carsten

回答

6

这是因为Monomorphism Restriction

这是一个技术问题(请查看链接,如果你对细节感兴趣),通常你永远不会看到,因为你添加签名或写下参数(不是无点风格)在你的模块 - 在GHCi它被禁用 - 你在这里有点不吉利。

为GHC这个较新的版本默认情况下启用编译模块,但停用GHCI(所以它会使用默认值作为epsilonhalbe告诉你)

要获得相同的行为,你可以运行

:set -XMonomorphismRestriction 

in GHCi

0

我认为你需要添加一个类型签名,ghci的是使用默认值,因此不会发生这种情况有