Gni*_*ruT 9 random io haskell functional-programming
I'm trying to show on Terminal a random number between 1 and 7...
nRandom :: IO ()
nRandom = do
number <- randomRIO (1,7)
putStrLn ("Your random number is: "++show number)
Run Code Online (Sandbox Code Playgroud)
...but ghc doesn't compile it and I get errors like:
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) }
Run Code Online (Sandbox Code Playgroud)
and,
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)
Run Code Online (Sandbox Code Playgroud)
Can anyone say me what am I doing wrong? Thanks ;)
Joh*_*n L 14
The problem is that both randomRIO and show are polymorphic, so the compiler doesn't know which type to pick for number. You can add a type annotation, e.g.
nRandom :: IO ()
nRandom = do
number <- randomRIO (1,7) :: IO Int
putStrLn ("Your random number is: "++show number)
Run Code Online (Sandbox Code Playgroud)
to help the compiler figure it out. I've attached the annotation to the expression randomRIO (1,7), which is why it's IO Int instead of just Int (which is numbers type).
| 归档时间: |
|
| 查看次数: |
2634 次 |
| 最近记录: |