我有这个函数“path”,它有3个参数:
path::String->String->String->IO()
path place1 dir place2 =
if place1 == "bedroom" && d == 'n' && place2 == "den"
then do
putStrLn "You are in a bedroom with a large, comfortable bed. It has been a long, tiresome day, and you would like nothing better than to go to sleep."
else
if place1 == "bedroom" && d == 'd' && place2 == "bed"
then describe "bed"
else
if place1 == "den" && d == 's' && place2 == "bedroom"
then describe "bedroom"
else
if place1 == "bed" && d == 'u' && place2 == "bedroom"
then describe "bedroom"
else putStrLn "Cannot go there!"
我想知道如果这是具有多个条件和多个if语句的正确方法?
答案 0 :(得分:12)
它不正确,但它不是惯用的(即习惯风格)。通常我们更喜欢看守if-then-else,比如@ user5402的答案。但是在你的情况下,你也只是将常量文字与==
进行比较,这意味着最好的方法是更进一步使用模式匹配(我将其格式化得更漂亮):
path :: String -> String -> String -> IO ()
path "bedroom" "n" "den" = putStrLn "You are in a bedroom with a large, comfortable bed. It has been a long, tiresome day, and you would like nothing better than to go to sleep."
path "bedroom" "d" "bed" = describe "bed"
path "den" "s" "bedroom" = describe "bedroom"
path "bed" "u" "bedroom" = describe "bedroom"
path _ _ _ = putStrLn "Cannot go there!"
答案 1 :(得分:3)
考虑使用警卫,例如:
path :: String -> String -> String -> IO ()
path place1 d place2
| place1 == "bedroom" && d == "n" && place2 == "den"
= putStrLn "You are in a bedroom ..."
| place1 == "bedroom" && d == "d" && place2 == "bed"
= describe "bed"
| place1 == "den" && d == "s" && place2 == "bedroom"
= describe "bedroom"
| place1 == "bed" && d == "u" && place2 == "bedroom"
= describe "bedroom"
| otherwise = putStrLn "Cannot go there!"
请注意,String
文字用双引号括起来。