For in OCaml

Here’s the OCaml translation of the Go “For” example:

Our example demonstrates various looping constructs in OCaml. Here are some basic types of loops.

(* The most basic type, with a single condition *)
let () =
  let i = ref 1 in
  while !i <= 3 do
    Printf.printf "%d\n" !i;
    i := !i + 1
  done

(* A classic initial/condition/after loop *)
let () =
  for j = 0 to 2 do
    Printf.printf "%d\n" j
  done

(* Another way of accomplishing the basic "do this N times" iteration *)
let () =
  List.iter (fun i -> Printf.printf "range %d\n" i) [0; 1; 2]

(* A loop that continues until explicitly broken *)
let () =
  try
    while true do
      Printf.printf "loop\n";
      raise Exit
    done
  with Exit -> ()

(* You can also continue to the next iteration of the loop *)
let () =
  for n = 0 to 5 do
    if n mod 2 = 0 then
      continue
    else
      Printf.printf "%d\n" n
  done

To run the program, save it as for.ml and use ocaml to execute it:

$ ocaml for.ml
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In OCaml, we use while loops for condition-based iteration, for loops for counting loops, and List.iter or other higher-order functions for iterating over collections. The continue keyword doesn’t exist in OCaml, so we use an if-else structure to skip iterations. The infinite loop with a break is simulated using an exception.

We’ll see some other looping forms later when we look at list comprehensions, recursive functions, and other data structures.