我有此函数“路径”,它带有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语句的正确方法?
这不是不正确的,但不是惯用语言(即习惯样式)。通常,我们喜欢使用警卫而不是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!"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句