首页 > 解决方案 > 如何显示两个输入是否相同

问题描述

我试图只比较两个用户输入,但我似乎无法让它工作并且不断出现解析错误。任何帮助将不胜感激。

main = do  
foo <- putStrLn "Enter two numbers."  
numone <- getLine
numtwo <- getLine  
putStrLn $ ("You entered " ++ numone ++ " and " ++ numtwo) 

if 
    numone == numtwo 
    then 
        putStrLn "They are the same"
          else
             putStrLn "They are not the same"

标签: haskell

解决方案


错误可能是由于本地版本和此处发布的版本之间缩进的微小变化而引起的。Haskell 中的缩进非常重要,因为编译器使用它来理解某些“块”的开始和结束位置。

此外,您可以删除该foo <-部分(这并没有错,但毫无用处)。所以重新格式化后我们得到:

main = do  
  putStrLn "Enter two numbers."  
  numone <- getLine
  numtwo <- getLine  
  putStrLn $ ("You entered " ++ numone ++ " and " ++ numtwo) 
  if numone == numtwo 
  then 
    putStrLn "They are the same"
  else
    putStrLn "They are not the same"

此外,现在您比较两个字符串。您可以将这些转换为Ints (或其他可读类型),例如readLn :: Read a => IO a

main = do  
  putStrLn "Enter two numbers."  
  numone <- readLn :: IO Int
  numtwo <- readLn :: IO Int
  putStrLn $ ("You entered " ++ show numone ++ " and " ++ show numtwo) 
  if numone == numtwo 
  then 
    putStrLn "They are the same"
  else
    putStrLn "They are not the same"

推荐阅读