Making Decisions
8 min · OCaml
Run different code depending on whether something is true.
Enemy 1 of 5
if / then / else as an expression
Just about every useful program needs to behave differently depending on its input — treat a large value differently from a small one, a valid entry differently from an invalid one. `if ... then ... else ...` is OCaml's way of choosing between two possible outcomes based on whether a condition is true or false.
Unlike many languages where `if` is purely a control-flow statement, in OCaml `if condition then a else b` is a genuine expression that produces a value — it evaluates to `a` when the condition is true, and to `b` when it's false. Because of this, OCaml requires both branches to have the *same type* — you can't have one branch return a string and the other return an integer, since the whole `if` expression needs one consistent type. If you omit the `else` entirely, both branches must produce `unit` (nothing), which is exactly the case in the example below: each branch is just a `print_endline` call, and `print_endline` returns `unit`.
Comparisons use `>`, `<`, `>=`, `<=` for ordering and `=` for equality (note: a single `=`, not `==` — `==` in OCaml means something more specialized, physical/reference equality, which is rarely what you want for comparing simple values like numbers). Mixing up `=` and `==` is a classic OCaml gotcha for people coming from C-family languages where `==` is the standard equality check.
Loading editor...