OCaml if Expressions
In OCaml, if is an expression: it evaluates to a value, like the ternary ? : operator in C or JavaScript. Both branches must have the same type.
let sign n = if n > 0 then "positive" else if n < 0 then "negative" else "zero"
let () =
print_endline (sign 12);
print_endline (sign (-3));
print_endline (sign 0)positive
negative
zero
The general form is if condition then e1 else e2. The condition must be a bool; there is no "truthy" 0 or empty string as in some languages.
Using the value
Because if produces a value, you can use it anywhere an expression is allowed: in a let, as a function argument, or inside arithmetic:
let shipping_cost total = if total >= 50.0 then 0.0 else 4.99
let () =
let basket = 42.0 in
let to_pay = basket +. shipping_cost basket in
Printf.printf "to pay: %.2f\n" to_pay;
Printf.printf "%d item%s\n" 1 (if 1 = 1 then "" else "s");
Printf.printf "%d item%s\n" 3 (if 3 = 1 then "" else "s")to pay: 46.99
1 item
3 items
Both branches must agree
If the branches have different types, the program does not compile:
let describe n = if n > 100 then "big" else n
let () = print_endline (describe 5)File "<source>", line 1, characters 44-45:
1 | let describe n = if n > 100 then "big" else n
^
Error: The value n has type int but an expression was expected of type string
The compiler inferred from the then branch that the result is a string, so returning the int n in the else branch is rejected.
if without else
You may leave out else only when the then branch has type unit. The missing branch is then (). This is used for side effects such as printing:
let warn_if_low battery =
if battery < 20 then Printf.printf "Battery low: %d%%\n" battery
let () =
warn_if_low 15;
warn_if_low 80;
print_endline "done"Battery low: 15%
done
Several actions in a branch
A branch is a single expression. To run several unit expressions in one branch, group them with parentheses or begin ... end:
let check_age age =
if age >= 18 then begin
print_string "adult: ";
print_endline "access granted"
end else begin
print_string "minor: ";
print_endline "access denied"
end
let () =
check_age 30;
check_age 12adult: access granted
minor: access denied
Warning: Without
begin ... end,if c then a; brunsbalways, because;has lower precedence thanif. It is parsed as(if c then a); b. This is a classic OCaml trap.
if or match?
For a chain of conditions on the same value, match with guards (covered later) is often clearer. For simple yes/no decisions, if is perfect:
| Situation | Prefer |
|---|---|
| A boolean condition | if ... then ... else |
Several specific values (0, 1, "quit") |
match |
| Taking apart data (lists, options, variants) | match |
Test yourself
What is the type of if x > 0 then 1.0 else 0.0?
boolintfloatunit
When can you omit the else branch?
- Never
- When the
thenbranch has typeunit - When the condition is true
- When the then branch returns an int
In if ok then print_string "a"; print_string "b", when is "b" printed?
- Only when ok is true
- Only when ok is false
- Always
- Never