Haskell Study Note (Lesson 4)

Lesson 4 Conditionals & Branching

Basic if - else Expressions

The basic structure of if-else is :

1
2
3
if conidition
then resultWhenTrue
else resultWhenfalse

For example, to judge whether a number is positive :

1
2
3
4
5
isPossive :: Int -> String
isPossive n =
if n > 0
then "Yes"
else "No"

Guard in Depth

Basic grammar :

1
2
3
4
functionName args
| condition1 = result1
| condition2 = result2
| otherwise = defaultResult

Note that the otherwise (Default Branch) is neccesary.

An example :

1
2
3
4
5
isPossive :: Int -> String
isPossive n
| n > 0 = "Positive"
| n < 0 = "Negative"
| otherwise = "Zeor"

Practice : Smart Shopping Assitant

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
shoppingAssistant :: Double -> (Double, String)
shoppingAssistant amount
| amount >= 500 =
let final = amount * 0.8
in (final, "Free shipping + 20 % off")
| amount >= 300 =
let final = amount * 0.9 + 30
in (final, "Shipping fee added + 10 % off")
| otherwise =
let final = amount + 30
in (final, "No discount, shipping fee added")



main :: IO ()
main = do
let a = 400.0
print (shoppingAssistant(a))

Note :

  1. To use guard, note the place of your =
  2. To output Triple, you can use print instead of putStrLn