Reputation: 455
I have this function "path" that takes 3 arguments:
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!"
I want to know how if this is the correct way of having multiple conditions and multiple if statements?
Upvotes: 6
Views: 814
Reputation: 18199
It's not incorrect, but it is not idiomatic (i.e. customary style). Usually we prefer guards to if-then-else, like in @user5402's answer. However in your case you are also just comparing to constant literals with ==
, which means the best way is to take it one step further and use pattern matching (I formatted it a bit prettier too):
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!"
Upvotes: 12
Reputation: 52057
Consider using guards, e.g.:
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!"
Note that String
literals an enclosed in double quotes.
Upvotes: 3