【问题标题】:Am I using randomRIO wrong?我使用 randomRIO 错了吗?
【发布时间】:2014-03-20 07:50:57
【问题描述】:

我正在尝试在终端上显示 1 到 7 之间的随机数...

nRandom :: IO ()
nRandom = do
    number <- randomRIO (1,7)
    putStrLn ("Your random number is: "++show number)   

...但是 ghc 没有编译它,我得到如下错误:

No instance for (Random a0) arising from a use of `randomRIO'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
  instance Random Bool -- Defined in `System.Random'
  instance Random Foreign.C.Types.CChar -- Defined in `System.Random'
  instance Random Foreign.C.Types.CDouble
    -- Defined in `System.Random'
  ...plus 33 others
In a stmt of a 'do' block: number <- randomRIO (1, 7)
In the expression:
  do { number <- randomRIO (1, 7);
       putStrLn ("Your random number is: " ++ show number) }
In an equation for `nRandom':
    nRandom
      = do { number <- randomRIO (1, 7);
             putStrLn ("Your random number is: " ++ show number) }

和,

No instance for (Num a0) arising from the literal `1'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
  instance Num Double -- Defined in `GHC.Float'
  instance Num Float -- Defined in `GHC.Float'
  instance Integral a => Num (GHC.Real.Ratio a)
    -- Defined in `GHC.Real'
  ...plus 37 others
In the expression: 1
In the first argument of `randomRIO', namely `(1, 7)'
In a stmt of a 'do' block: number <- randomRIO (1, 7)

谁能告诉我我做错了什么?谢谢;)

【问题讨论】:

    标签: haskell random io functional-programming


    【解决方案1】:

    问题是randomRIOshow 都是多态的,所以编译器不知道为number 选择哪种类型。您可以添加类型注释,例如

    nRandom :: IO ()
    nRandom = do
        number <- randomRIO (1,7) :: IO Int
        putStrLn ("Your random number is: "++show number)
    

    帮助编译器解决这个问题。我已将注释附加到表达式randomRIO (1,7),这就是为什么它是IO Int 而不仅仅是Int(这是numbers 类型)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      相关资源
      最近更新 更多