TExcelTAD
Home › OCaml › OCaml for and while Loops

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:

ocaml · try it yourself
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"
  done
1 2 3 4 5 
10 9 8 7 

Rules worth knowing:

  • The loop variable is an immutable int local to the body. You cannot assign to it.
  • There is no step size: to count by 2, multiply (2 * i) or use a while loop.
  • There is no break or continue. Use a while loop with a condition, or an exception, to exit early.
  • The body must have type unit, and the loop itself has type unit.

A multiplication table

ocaml · try it yourself
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:

ocaml · try it yourself
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:

ocaml · try it yourself
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.

ocaml · try it yourself
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 functional
2418 2418

Test yourself

How many times does for i = 2 to 5 do ... done run its body?

  1. 3
  2. 4
  3. 5
  4. 2

How do you count down from 10 to 1?

  1. for i = 10 to 1
  2. for i = 10 downto 1
  3. for i = 10 to 1 step -1
  4. for i in 10..1

OCaml has no break. Which is a valid way to exit a for loop early?

  1. return
  2. Raise an exception and catch it outside the loop
  3. Assign to the loop variable
  4. exit_loop ()