使用randomR生成随机值元组

时间:2014-11-12 16:06:07

标签: haskell random

我正在处理this introduction to the State monad,在其中一个介绍性示例中,我们遇到了以下代码(在文章中称为clumsyRollDice)...

rollDice3 :: (Int, Int)
rollDice3 = (n,m)
  where
    (n,g) = randomR (1,6) (mkStdGen 0)
    (m,_) = randomR (1,6) g

...不编译(如下所示)。

我错过了什么?自示例发布以来,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)

更新:
以下修复了代码,但我仍然很好奇:在运行代码的逐字版本时,更改了(即在编译器/等中)导致错误的内容:

rollDice3 :: (Int, Int)
rollDice3 = (n,m)
  where
    (n,g) = randomR ((1::Int),6) (mkStdGen 0)
    (m,_) = randomR (1,6) g

1 个答案:

答案 0 :(得分:1)

考虑此文件,保存为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吗?

在这个邮件列表主题中讨论了一个非常类似的案例:

Unexpected ambiguity in a seemingly valid Haskell 2010 program

在wiki上详细讨论了单态限制:

Monomorphism restriction