
On Saturday 24 July 2010 21:36:14, michael rice wrote:
This works:
Prelude System.Random> do { randomRIO (1,6) >>= (\x -> putStrLn $ "Value = " ++ show x) } Value = 5
So does this:
Prelude System.Random> do { x <- randomRIO (1,6); putStrLn $ "Value = " ++ show x } Value = 2
But not this:
1 import Control.Monad 2 import System.Random 3 4 foo :: IO () 5 foo = do 6 x <- randomRIO (1,6) 7 putStrLn $ "Value = " ++ show x
foo.hs:6:18: Ambiguous type variable `t' in the constraints: `Num t' arising from the literal `1' at foo.hs:6:18 `Random t' arising from a use of `randomRIO' at foo.hs:6:7-21 Probable fix: add a type signature that fixes these type variable(s) Failed, modules loaded: none. Prelude System.Random>
The x has type (Num a, Random a) => a so GHC doesn't know which type to choose. GHCi uses extended defaulting rules and picks Integer. Fix, tell GHC which type to choose: putStrLn $ "Value = " ++ show (x :: Integer) or x <- randomRIO (1,6) :: IO Integer
Or this:
1 import Control.Monad 2 import System.Random 3 4 foo :: IO () 5 foo = randomRIO (1,6) >>= (\x -> putStrLn $ "Value = " ++ show x)
foo.hs:5:17: Ambiguous type variable `t' in the constraints: `Num t' arising from the literal `1' at foo.hs:5:17 `Random t' arising from a use of `randomRIO' at foo.hs:5:6-20 Probable fix: add a type signature that fixes these type variable(s) Failed, modules loaded: none.
How to fix?
Michael