haskell 解析来自输入的浮点值,结果为“异常:无分析”

2vuwiymt  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(133)

我写了这段代码:

calculIOTest :: IO ()
calculIOTest = do
   putStrLn "Give me two numbers"
   l1 <- getLine
   let x1 = read l1 
   l2 <- getLine
   let x2 = read l2 
   print (x1 + x2)

我想要的代码,采取两个数字,并返回总和。如果我用两个整数测试函数,它可以工作,但如果我放一个浮点数,那么错误就有问题:

***Exception: Prelude.read: no parse

我本来可以理解一个字符串和一个数字,但在这里我很难理解是什么导致了这个问题。
我试着回顾阅读是如何工作的,如果我这样做的话:

(read 10000.9) + (read 1115)

它给了我一些错误:

Could not deduce (Fractional String)
        arising from the literal ‘10000.9’
      from the context: (Read a, Num a)
        bound by the inferred type of it :: (Read a, Num a) => a
        at <interactive>:135:1-28

Could not deduce (Num String) arising from the literal ‘1115’
      from the context: (Read a, Num a)
        bound by the inferred type of it :: (Read a, Num a) => a
        at <interactive>:135:1-28

我想知道为什么它在我的代码中不起作用,以及错误在哪里防止读取?

cyej8jka

cyej8jka1#

由于添加了x1x2,编译器可以推断出它们必须具有Num示例和default type for Num a is Integer。因此,隐式地,您的代码等效于以下内容:

calculIOTest :: IO ()
calculIOTest = do
   putStrLn "Give me two numbers"
   l1 <- getLine
   let x1 = (read l1 :: Integer)
   l2 <- getLine
   let x2 = (read l2 :: Integer)
   print (x1 + x2)

显然你不能把一个浮点数表示解析成Integer。要接受Double s,您需要做的就是显式地注解该类型:

calculIOTest :: IO ()
calculIOTest = do
   putStrLn "Give me two numbers"
   l1 <- getLine
   let x1 = (read l1 :: Double)
   l2 <- getLine
   let x2 = (read l2 :: Double)
   print (x1 + x2)

如果你包含了必要的",你的裸读(read 10000.9) + (read 1115)也会遇到同样的问题(read需要一个String,而不是浮点数或整数)

read "10000.9" + read "1115"

too的结果是***Exception: Prelude.read: no parse,修复是相同的,注解你想要的类型。

相关问题