OCaml for and while Loops
Recursion and higher-order functions handle most repetition in OCaml, but the language also has classic imperative loops. They are the natural choice for working with arrays, counters and other mutable state.
for loops
A for loop counts through a range of integers, inclusive at both ends. Use downto to count down:
let () =
for i = 1 to 5 do
Printf.printf "%d " i
done;
print_newline ();
for i = 10 downto 7 do
Printf.printf "%d " i
done;
print_newline ();
for i = 3 to 1 do
print_endline "never runs: 3 is already past 1"
done1 2 3 4 5
10 9 8 7
Rules worth knowing:
- The loop variable is an immutable
intlocal to the body. You cannot assign to it. - There is no step size: to count by 2, multiply (
2 * i) or use awhileloop. - There is no
breakorcontinue. Use awhileloop with a condition, or an exception, to exit early. - The body must have type
unit, and the loop itself has typeunit.
A multiplication table
let () =
for row = 1 to 4 do
for col = 1 to 6 do
Printf.printf "%4d" (row * col)
done;
print_newline ()
done 1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
while loops
A while loop repeats as long as its condition is true. The condition usually depends on a reference:
let collatz_steps start =
let n = ref start and steps = ref 0 in
while !n <> 1 do
n := if !n mod 2 = 0 then !n / 2 else (3 * !n) + 1;
incr steps
done;
!steps
let () = List.iter (fun s -> Printf.printf "%d takes %d steps\n" s (collatz_steps s)) [ 1; 6; 27 ]1 takes 0 steps
6 takes 8 steps
27 takes 111 steps
Leaving a loop early
Since there is no break, you have three options:
let numbers = [| 4; 8; 15; 16; 23; 42 |]
(* 1. a while loop with a "found" flag *)
let index_of_first_odd_v1 a =
let i = ref 0 and found = ref None in
while !found = None && !i < Array.length a do
if a.(!i) mod 2 = 1 then found := Some !i;
incr i
done;
!found
(* 2. raise an exception to jump out of a for loop *)
exception Found of int
let index_of_first_odd_v2 a =
try
for i = 0 to Array.length a - 1 do
if a.(i) mod 2 = 1 then raise (Found i)
done;
None
with Found i -> Some i
(* 3. a recursive function: often the clearest *)
let index_of_first_odd_v3 a =
let rec go i = if i >= Array.length a then None else if a.(i) mod 2 = 1 then Some i else go (i + 1) in
go 0
let show = function Some i -> string_of_int i | None -> "none"
let () =
Printf.printf "%s %s %s\n"
(show (index_of_first_odd_v1 numbers))
(show (index_of_first_odd_v2 numbers))
(show (index_of_first_odd_v3 numbers))2 2 2
The standard library also helps: Array.find_index (OCaml 5.1+) does exactly this.
Loops versus iterators
| Task | Imperative | Functional |
|---|---|---|
| Do something for each element | for i = 0 to n - 1 do ... a.(i) ... done |
Array.iter f a, List.iter f l |
| Compute a total | ref + loop |
fold_left |
| Build a new collection | Array.make + loop |
Array.init, List.map |
| Repeat until a condition | while |
a recursive function |
Both styles compile to efficient code. Use loops when they make the intent clearer, such as nested index loops over a matrix, and iterators when you are transforming data.
let () =
(* the same computation in both styles *)
let total = ref 0 in
for i = 1 to 100 do
if i mod 3 = 0 || i mod 5 = 0 then total := !total + i
done;
let functional =
List.init 100 (fun i -> i + 1)
|> List.filter (fun i -> i mod 3 = 0 || i mod 5 = 0)
|> List.fold_left ( + ) 0
in
Printf.printf "%d %d\n" !total functional2418 2418
Test yourself
How many times does for i = 2 to 5 do ... done run its body?
- 3
- 4
- 5
- 2
How do you count down from 10 to 1?
for i = 10 to 1for i = 10 downto 1for i = 10 to 1 step -1for i in 10..1
OCaml has no break. Which is a valid way to exit a for loop early?
return- Raise an exception and catch it outside the loop
- Assign to the loop variable
exit_loop ()