Haskell 使用randomR生成随机值的元组
我正在研究,在一个介绍性示例中,我们遇到了以下代码(本文中称为Haskell 使用randomR生成随机值的元组,haskell,random,Haskell,Random,我正在研究,在一个介绍性示例中,我们遇到了以下代码(本文中称为clumsyRollDice) …无法编译(如下所示) 我错过了什么?自示例发布以来,System.Random中的函数/类之一的实现是否发生了变化 statemonad.hs:15:5: No instance for (Random t0) arising from the ambiguity check for ‘g’ The type variable ‘t0’ is ambiguous W
clumsyRollDice
)
…无法编译(如下所示)
我错过了什么?自示例发布以来,System.Random
中的函数/类之一的实现是否发生了变化
statemonad.hs:15:5:
No instance for (Random t0)
arising from the ambiguity check for ‘g’
The type variable ‘t0’ is ambiguous
When checking that ‘g’ has the inferred type ‘StdGen’
Probable cause: the inferred type is ambiguous
In an equation for ‘rollDice3’:
rollDice3
= (n, m)
where
(n, g) = randomR (1, 6) (mkStdGen 0)
(m, _) = randomR (1, 6) g
statemonad.hs:16:13:
Could not deduce (RandomGen t0) arising from a use of ‘randomR’
from the context (Random t, Num t)
bound by the inferred type of m :: (Random t, Num t) => t
at statemonad.hs:16:5-27
The type variable ‘t0’ is ambiguous
Note: there is a potential instance available:
instance RandomGen StdGen -- Defined in ‘System.Random’
In the expression: randomR (1, 6) g
In a pattern binding: (m, _) = randomR (1, 6) g
In an equation for ‘rollDice3’:
rollDice3
= (n, m)
where
(n, g) = randomR (1, 6) (mkStdGen 0)
(m, _) = randomR (1, 6) g
Failed, modules loaded: none.
(0.00 secs, 0 bytes)
更新:下面修复了代码,但我仍然很好奇:在运行代码的逐字版本时,是什么更改(即在编译器/etc中)导致了错误:
rollDice3 :: (Int, Int)
rollDice3 = (n,m)
where
(n,g) = randomR ((1::Int),6) (mkStdGen 0)
(m,_) = randomR (1,6) g
考虑此文件,另存为
test.hs
module Main (main, clumsyRollDice) where
import System.Random
clumsyRollDice :: (Int, Int)
clumsyRollDice = (n, m)
where
(n, g) = randomR (1,6) (mkStdGen 0)
(m, _) = randomR (1,6) g
main = putStrLn (show clumsyRollDice)
此文件在ghc test.hs
下编译,但在ghc test.hs-XNoMonomorphismRestriction
下失败,错误与您报告的非常类似。您是否在ghci中设置了NoMonomonomorphismRestriction
此邮件列表线程中讨论了一个非常类似的案例:
wiki上详细讨论了单态限制:
自2010年起,randomR的实施依赖于randomIvalIntegral,所以“最近”没有任何变化哈哈,公平的说,我在说“最近”时应该更小心是的,这正是错误的原因。我确实打开了单态限制。(事实上,我正在运行GHC7.8.3,默认情况下它是打开的。)谢谢
module Main (main, clumsyRollDice) where
import System.Random
clumsyRollDice :: (Int, Int)
clumsyRollDice = (n, m)
where
(n, g) = randomR (1,6) (mkStdGen 0)
(m, _) = randomR (1,6) g
main = putStrLn (show clumsyRollDice)