Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
打印两个数字的和Haskell_Haskell - Fatal编程技术网

打印两个数字的和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))