2014-11-08 66 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文字的双引号括起来。