2014-11-08 70 views
6

我有這個功能「路徑」這3個參數:如何在haskell中編寫嵌套的if語句?

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

BTW,它將可能是一個好主意,改變第二個參數的類型,使其比「Char」或「String」更有意義。 – leftaroundabout 2014-11-09 01:10:41

回答

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!" 
+0

是的,這是一個很好的習慣用法。 – ErikR 2014-11-09 01:23:19

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文字的雙引號括起來。