6

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?

1
  • BTW, it would probably a good idea to change the second argument's type so something more meaningful than Char or String. Commented Nov 9, 2014 at 1:10

2 Answers 2

12

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!"
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.