我在摆弄IO,但不理解以下错误:
* 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)
代码
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)
PS 我不知道编译器是否应该推断readLine
的实例类型并在2
方法中使用useInt
进行添加?
答案 0 :(得分:3)
2
在Haskell中不仅是Int
,而且是任何数字类型,包括Float,Double,Integer,...
。其类型为Num a => a
-一种适合每种数字类型的多态类型。
因此,您可以改用(2::Int)
。然后您会发现(2::Int) + readLine
是类型错误,因为readLine :: Int
是错误的,所以我们只会得到readLine :: IO Int
。
您可以尝试使用此方法
useInt :: IO ()
useInt = do
i <- readLine
putStrLn . show (2 + i :: Int)