Haskell读取不带注释的函数



haskell read函数是否隐式地将一种数据类型转换为另一种?

import IO
main = do
putStrLn "Enter an interger: "
num <- getLine
putStr "Value + 3 is "
putStrLn (show((read num) + 3))

那么,haskell解释器会自动将num的数据类型从字符串更改为int,以处理"+3"?

read具有类型Read a => String -> a,这意味着它可以将String转换为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))
|      

这里使用的是

show :: Show a => a -> String
read :: Read a => String -> a
(+) :: Num a => a -> a -> a
3 :: Num a => a

在相同类型的CCD_ 15上。因此,Haskell搜索满足Show a, Read a, Num a的类型a

原则上,这将被拒绝,因为类型不明确,但Haskell为Num指定了一个特殊的规则,导致a被默认为Integer。由于这也满足ShowRead,因此程序类型检查。

最新更新