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?
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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With