Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write nested if statements in haskell?

Tags:

haskell

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?

like image 935
Linda Su Avatar asked Nov 08 '14 23:11

Linda Su


1 Answers

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!"
like image 110
Ørjan Johansen Avatar answered Sep 29 '22 06:09

Ørjan Johansen