我试图重写那个正在工作的程序:
nameIOite :: IO ()
nameIOite = do
putStrLn "What's your name ?"
name <- getLine
if name `elem` ["Simon","John","Phil"]
--if name == "Simon" || name == "John" || name == "Phil" also works but is ugly.
then putStrLn "I think Haskell is a great programming language."
else if name == "Koen"
then putStrLn "I think debugging Haskell is fun."
else putStrLn "I don't know your name."
这是使用 if/then/else 完成的(因此后缀 ite in nameIOite
)
然后我尝试使用警卫:
nameIOg :: IO ()
nameIOg = do
putStrLn "What's your name ?"
name <- getLine
let answer
| name `elem` ["Simon","John","Phil"] = "I think Haskell is a great programming language."
| name == "Koen" = "I think debugging Haskell is fun."
| otherwise = "I don't know your name."
putStrLn answer
这没有用:
test.hs:6:9: error:
parse error (possibly incorrect indentation or mismatched brackets)
|
6 | | name `elem` ["Simon","John","Phil"] = "I think Haskell is a great programming language."
| ^
Failed, no modules loaded.
经过一些实验,解决方案结果证明再次缩进警卫(这对我来说根本不清楚):
nameIOg :: IO ()
nameIOg = do
putStrLn "What's your name ?"
name <- getLine
let answer
| name `elem` ["Simon","John","Phil"] = "I think Haskell is a great programming language."
| name == "Koen" = "I think debugging Haskell is fun."
| otherwise = "I don't know your name."
putStrLn answer
Ok, one module loaded.
这种双重缩进是从哪里来的,有没有办法写得更优雅?
(顺便说一句,我在查看我的 wikibook.hs 文件时偶然发现了这一点。)
例子来源:那里
解决方案: 有