Bercovici Adrian
Bercovici Adrian

Reputation: 9370

Ambigous type variable that prevents the constraint

I am fiddling around with IO and i do not understand the following error :

* Ambiguous type variable `a0' arising from a use of `readLine'
      prevents the constraint `(Console a0)' from being solved.
      Probable fix: use a type annotation to specify what `a0' should be.
      These potential instance exist:
        instance Console Int -- Defined at Tclass.hs:8:14
    * In the second argument of `(+)', namely `readLine'
      In the second argument of `($)', namely `(2 + readLine)'
      In the expression: putStrLn . show $ (2 + readLine)
   |
17 |     useInt =putStrLn . show $ (2+readLine)

Code

module Tclass where
    import System.Environment

    class Console a where
        writeLine::a->IO()
        readLine::IO a

    instance Console Int where
        writeLine= putStrLn . show 

        readLine = do
            a <- getLine
            let b= (read  a)::Int
            return b

    useInt::IO()
    useInt =putStrLn . show $ (2+readLine)  

P.S i do not understand shouldn't the compiler infer the type of the instance for readLine and make the addition with 2 in the useInt method ?

Upvotes: 0

Views: 233

Answers (1)

chi
chi

Reputation: 116174

2 is not only an Int in Haskell but it is of any numeric type, including Float,Double,Integer,.... Its type is Num a => a -- a polymorphic type fitting each numeric type.

So, you could use (2::Int) instead. Then you'll discover that (2::Int) + readLine is a type error, since readLine :: Int is wrong, we only get readLine :: IO Int.

You can try this, instead

useInt :: IO ()
useInt = do
   i <- readLine
   putStrLn . show (2 + i :: Int)

Upvotes: 3

Related Questions