打印两个数字的和Haskell
如何打印两个数字之和的结果打印两个数字的和Haskell,haskell,Haskell,如何打印两个数字之和的结果 main:: IO() main = do putStrLn "Insert the first value: " one <- getLine putStrLn "Insert the second value: " two <- getLine putStrLn "The result is:" print (one+two) 我猜你的错误与不使用pare
main:: IO()
main = do putStrLn "Insert the first value: "
one <- getLine
putStrLn "Insert the second value: "
two <- getLine
putStrLn "The result is:"
print (one+two)
我猜你的错误与不使用parens有关 另外,由于
getLine
生成字符串,因此需要将其转换为正确的类型。我们可以使用read
从中获取一个数字,但如果无法解析字符串,则可能会导致错误,因此您可能希望在读取之前检查它是否仅包含数字
print (read one + read two)
根据优先级,变量可能被解析为属于print
的参数,而不是+
。通过使用parens,我们确保变量与+
相关联,并且只有结果与打印相关
最后,确保压痕是正确的。您在此处粘贴的方式与do表达式不符。第一个putStrLn应该与其他putStrLn处于相同的缩进级别-至少ghc会抱怨它。尝试使用readLn
而不是getLine
getLine
在IO
monad中返回String
,无法添加String
s
readLn
具有多态返回类型,编译器推断返回类型为Integer
(在IO
monad中),因此您可以添加它们。您可以使用read::read a=>String->a
main:: IO()
main = do putStrLn "Insert the first value: "
one <- getLine
putStrLn "Insert the second value: "
two <- getLine
putStrLn "The result is:"
print ((read one) + (read two))
main::IO()
main=do putStrLn“插入第一个值:”
更新了一个@user1966757。需要使用read
将其转换为数字:)谢谢,这也是一个识别问题。@AndrewC是的,它们确实不需要read。它之前只是一个打印一加二
,在这一点上它会导致一个错误:)更具建设性地使用GHC。如果您喜欢使用解释器而不是编译器,则可以使用GHC附带的runghc
程序。@CatPlusPlus Hugs可以用于此类代码。runghc不是交互式口译员。ghci是,而且使用起来也很好。您的语句必须对齐,并且有不必要的括号打印(读一+读二)
main:: IO()
main = do putStrLn "Insert the first value: "
one <- getLine
putStrLn "Insert the second value: "
two <- getLine
putStrLn "The result is:"
print ((read one) + (read two))