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.
To run the program, save it as for.ml and use ocaml to execute it:
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.