我使用randomRIO错了吗?

时间:2014-03-20 07:50:58

标签: haskell random io functional-programming

我试图在终端上显示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)

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

1 个答案:

答案 0 :(得分:14)

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

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

帮助编译器搞清楚。我已将注释附加到表达式randomRIO (1,7),这就是IO Int而不仅仅是Intnumber类型)的原因。