String->String->IO() path place1 ...">

How to write nested if statements in 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 is the correct way to have multiple conditions and multiple if statements?

+6
source share
2 answers

This is not true, but it is not idiomatic (i.e. the usual style). Usually we prefer if-then-else guards, as in @ user5402's answer. However, in your case, you also simply compare with constant literals with == , which means that the best way is to do this one step further and use pattern matching (I formatted it a bit more):

 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!" 
+12
source

Consider the use of protective devices, for example:

 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 are enclosed in double quotes.

+3
source

Source: https://habr.com/ru/post/977929/


All Articles