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

OCaml, lesson 4

Making decisions

Programs need to behave differently depending on their data: charge a child less, warn when a value is too high, and so on. OCaml gives you two tools for this: if and match.

if is an expression

In OCaml, if ... then ... else ... does not just run one branch, it produces a value:

Because the whole if is a value, both branches must have the same type. if x > 0 then "yes" else 0 is a type error: one branch is a string, the other an int.

You can chain conditions with else if:

An if without else is allowed only when the branch returns unit, for example a print. When a branch needs several steps, wrap them in (or parentheses):

2 exercises to try what you just read.

Exercise 1

Ticket price

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

then
begin ... end

Comparison operators

OperatorMeaning
=equal
<>not equal
< >less / greater than
<= >=less / greater or equal

They work on numbers, strings (alphabetical order), characters and more, but both sides must have the same type. Be careful: OCaml also has == and !=, which test whether two values are the same object in memory. For ordinary comparisons always use = and <>.

Boolean operators

Combine conditions with && (and), || (or) and not:

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

Pattern matching with match

When you compare one value against several cases, match is cleaner than a chain of ifs:

OCaml tries the patterns from top to bottom and uses the first one that fits. _ matches anything, so it acts as "otherwise". 6 | 7 matches either value. If you forget a case, the compiler warns that the match is not exhaustive, which is a great way to catch bugs before they happen.

A pattern can carry an extra condition with when:

Here t is a new name bound to the value being matched, and the when guard decides whether the case applies. Use if for a simple yes/no choice, and match when there are several shapes or ranges to handle.

Further reading

  • Basic Data Types and Pattern Matching
  • A Tour of OCaml: conditional expressions and pattern matching

A cinema charges by age: children under 13 pay 5, people aged 65 or older pay 7, and everyone else pays 12. Read an age (a whole number, 0 or more) and print the price.

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. Read a year and print leap or common.

Sample input:

Sample output:

let () =
  let temp = int_of_string (read_line ()) in
  let advice = if temp > 25 then "Wear a hat" else "Bring a jacket" in
  print_endline advice
let size = if n < 10 then "small" else if n < 100 then "medium" else "large"
if score > best then begin
  print_endline "New record!";
  print_endline "Well done."
end
let can_ride = age >= 8 && height >= 120
let weekend = day = "Sat" || day = "Sun"
let weekday = not weekend
let day_name n =
  match n with
  | 1 -> "Monday"
  | 2 -> "Tuesday"
  | 6 | 7 -> "Weekend"
  | _ -> "Some other day"
let describe temp =
  match temp with
  | t when t < 0 -> "freezing"
  | t when t < 20 -> "mild"
  | _ -> "warm"
70
Price: 7
2024
leap