Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 40 ยท Language Basics

Conditionals and Comparison in OCaml

Use if, then, else as an expression in OCaml, chain conditions, combine booleans, understand why both branches share a type, and compare values safely.

In OCaml, if is an expression: it produces a value, like the ternary operator ?: in other languages. That small fact shapes how conditionals are written and what the compiler demands of them.

if / then / else

OCAML
let sign n =
  if n > 0 then "positive"
  else if n < 0 then "negative"
  else "zero"
OCAML
# sign 5;;
- : string = "positive"

The condition must be a bool. There are no parentheses required around it, no braces and no return. The whole if ... else ... evaluates to the value of the branch that runs.

Both branches must have the same type

Because the if expression has one type, then and else must agree:

OCAML
let bad n = if n > 0 then "yes" else 0
(* Error: ... has type int but an expression was expected of type string *)

That rule rules out a whole family of bugs where one branch returns something unexpected.

if without else

An if without else is allowed only when the then branch has type unit, because the missing else is implicitly ():

OCAML
let warn n =
  if n > 100 then print_endline "big number"
OCAML
let broken n = if n > 0 then 5
(* Error: this expression has type int but an expression was expected of type unit *)

Several statements in a branch

A branch is a single expression. To run several in sequence, wrap them in begin ... end (or parentheses):

OCAML
let report n =
  if n < 0 then begin
    print_endline "negative!";
    print_endline "check your input"
  end else
    print_endline "fine"

A common mistake is forgetting begin/end: if c then a; b runs b always, because ; ends the if expression.

Comparison operators

=, <>, <, >, <= and >= work on any two values of the same type:

OCAML
# 3 = 3;;
- : bool = true
# "abc" < "abd";;
- : bool = true
# (1, 2) <= (1, 3);;
- : bool = true
# [1; 2] = [1; 2];;
- : bool = true

Be careful with floats: nan = nan is false. And never compare functions or values containing functions with =; it raises Invalid_argument "compare: functional value".

The function compare a b returns a negative number, zero or a positive number (like C's strcmp) and is what you pass to List.sort:

OCAML
# compare 2 10;;
- : int = -1

Boolean logic

OCAML
let in_range lo hi x = x >= lo && x <= hi
let is_weekend d = d = "Sat" || d = "Sun"
let valid x = not (x < 0)

&& and || short-circuit, so x <> 0 && 100 / x > 5 is safe.

Chains: when to use match instead

A long chain of ifs that tests one value is clearer as match:

OCAML
let name_of_digit d =
  match d with
  | 0 -> "zero"
  | 1 -> "one"
  | 2 -> "two"
  | _ -> "many"

match can also add conditions with when guards:

OCAML
let classify n =
  match n with
  | 0 -> "zero"
  | n when n < 0 -> "negative"
  | n when n mod 2 = 0 -> "positive even"
  | _ -> "positive odd"

Pattern matching is the heart of OCaml and gets a whole chapter later.

Using if inside other expressions

Since if is an expression it can appear anywhere a value can:

OCAML
let message count =
  "You have " ^ string_of_int count ^ (if count = 1 then " item" else " items")

let abs_diff a b = (if a > b then a - b else b - a)

Keep the parentheses around an if that is part of a larger expression, because if has low precedence and would otherwise swallow what follows.

A stand-in: if as an expression

JavaScript's ternary operator is the closest equivalent. The stand-in includes a check that both branches have the same type, mimicking the compiler.

JS Stand-in: both branches share a type

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is if x > 0 then "yes" else 0 rejected?

    An if expression has one type, so then and else must have the same type.
  2. 2. When may you leave out else?

    A missing else means else (), so the then branch must also be unit.
  3. 3. How do you run two statements in one branch?

    A branch is one expression; begin ... end groups a sequence into one expression.
  4. 4. What does compare 2 10 return?

    compare a b is negative when a < b, zero when equal, positive when a > b.

Summary

  • if is an expression; both branches must have the same type.
  • Without else, the branch must be unit.
  • Use begin ... end to group several statements.
  • Comparisons are polymorphic and structural; compare gives an ordering.
  • Prefer match for many alternatives on one value.

Next: Type inference