haskell 读取函数是否将数据类型隐式转换为另一种数据类型?
import IO
main = do
putStrLn "Enter an interger: "
num <- getLine
putStr "Value + 3 is "
putStrLn (show((read num) + 3))
那么,haskell 解释器会自动将 num 的数据类型从 string 更改为 int 以处理 '+ 3' 吗?
read
有 type Read a => String -> a
,这意味着它可以将 aString
转换为作为Read
类型类实例的任何类型。它将使用哪种类型取决于周围的代码。在这种情况下,您编写read num + 3
. 该+
运营商还重载工作对任何类型是一个实例Num
,所以类型read num + 3
为(Read a, Num a) => a
。Haskell 有一种机制,只要Num
类型类保留在表达式的最终类型中,就会选择默认类型。在这种情况下,它默认为Integer
,因此最终类型为Integer
。
您可以通过启用-Wtype-defaults
也包含在-Wall
以下内容中的警告来查看此操作:
Test.hs:5:15: warning: [-Wtype-defaults]
• Defaulting the following constraints to type ‘Integer’
(Show a0) arising from a use of ‘show’ at Test.hs:5:15-34
(Num a0) arising from a use of ‘+’ at Test.hs:5:20-33
(Read a0) arising from a use of ‘read’ at Test.hs:5:21-28
• In the first argument of ‘putStrLn’, namely
‘(show ((read num) + 3))’
In a stmt of a 'do' block: putStrLn (show ((read num) + 3))
In the expression:
do putStrLn "Enter an interger: "
num <- getLine
putStr "Value + 3 is "
putStrLn (show ((read num) + 3))
|
5 | putStrLn (show((read num) + 3))
|
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句