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)
...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) }
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)
Can anyone say me what am I doing wrong? Thanks ;)
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)
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 number
s type).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With