Learn/Haskell/4. Making decisions
Lesson 4 of 8
Sign in

Haskell, lesson 4

Making decisions

Programs need to choose: charge shipping only on small orders, warn when a battery is low. In Haskell a decision is not a statement that runs one block or another. It is an expression that produces one value or another.

if-then-else

This defines a small function fee that takes the order total and returns the fee. (You will learn functions properly in lesson 6; for now, read fee total = ... as "the fee for a total is ...".)

Because if must always produce a value, the else is required, and both branches must have the same type. You can use if anywhere a value fits, including inside main:

Comparison and boolean operators

2 exercises to try what you just read.

Exercise 1

What's the weather like?

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

OperatorMeaning
==equal
/=not equal (note: not !=)
< <= > >=ordering
&&and
||or
nota function that flips a Bool: not isOpen

&& and || are lazy: if the left side decides the answer, the right side is never evaluated.

Guards

When there are more than two cases, nested ifs get messy. Guards are the idiomatic alternative. Each line starts with |, then a condition, then = and the result. Haskell tries them from top to bottom and uses the first one that is True:

otherwise is simply another name for True, so it catches everything left over. Always end with it, or a value that matches no guard will crash the program.

case and pattern matching

case compares a value against patterns, which are shapes the value can have. A literal matches exactly; _ matches anything:

You can also match patterns directly in the function definition, one equation per case. This is very common in Haskell:

The equations are tried in order, so put the specific cases first and the catch-all last.

Keeping IO thin

A good Haskell habit: put the decision in a pure function (no IO), and keep main small. main reads the input, calls the function, and prints the result. Pure functions are easier to test and reason about because they always give the same output for the same input.

Further reading

  • A Gentle Introduction to Haskell: Case expressions and pattern matching
  • Haskell 2010 Report: Conditionals and case expressions
  • Prelude: Bool, otherwise, not

Write describe :: Int -> String with guards, then use it in main. Read a whole-number temperature in Celsius and print one word:

  • below 0: freezing
  • 0 to 15: cold
  • 16 to 25: mild
  • above 25: hot

Sample input:

Sample output:

A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap years only if they are also divisible by 400. Write isLeap :: Int -> Bool, read a year, and print either <year> is a leap year or <year> is not a leap year.

Sample input:

Sample output:

fee :: Int -> Int
fee total = if total >= 50 then 0 else 5
main :: IO ()
main = do
  battery <- readLn :: IO Int
  putStrLn (if battery < 20 then "Low battery!" else "Battery OK")
grade :: Int -> String
grade score
  | score >= 90 = "A"
  | score >= 80 = "B"
  | score >= 70 = "C"
  | otherwise   = "keep practising"
dayType :: String -> String
dayType day = case day of
  "Sat" -> "weekend"
  "Sun" -> "weekend"
  _     -> "weekday"
describe :: Int -> String
describe 0 = "none"
describe 1 = "one"
describe _ = "many"
18
mild
2024
2024 is a leap year