提问人:Slayteuse 提问时间:4/30/2023 最后编辑:cafce25Slayteuse 更新时间:4/30/2023 访问量:87
从输入解析浮点值会导致“异常:无解析”
Parsing floating point values from input results in "exception: no parse"
问:
我写了这个代码:
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
我想了解为什么它在我的代码中不起作用,以及读取时错误在哪里防止?
答:
5赞
cafce25
4/30/2023
#1
由于您正在添加,编译器可以推断这些必须具有实例,并且 Num a
的默认类型为 Integer
。因此,隐式代码等同于以下内容:x1
x2
Num
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)
显然,您不能将浮点表示解析为 .
要接受 s,您所要做的就是显式注释该类型:Integer
Double
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)
如果您包含必要的(需要 not floats 或 ints),您的裸读将遇到同样的问题(read 10000.9) + (read 1115)
"
read
String
read "10000.9" + read "1115"
结果也一样,修复是相同的,注释您想要的类型。***Exception: Prelude.read: no parse
评论
readLn
readLn