Imperative Programming in OCaml

Imperative Vs Functional Programming

So far, what I’ve done in OCaml is functional, i.e., I declare functions and the output value of a function depends only on the arguments that are passed to the function.  The data structures covered are mostly immutable (not able to change).  In contrast, with imperative programming, computations are structured as sequences of instructions that operate by making modifications to the state of the program.  OCaml also supports refs, a single mutable value and mutable data structures including arrays and mutable record fields.  Control-flow constructs including for and while loops are also supported.


  • Defining an array: start with [|, end with |], separating each element with ;.  E.g.:
    let numbers = [| 1; 2; 3; 4 |];;

    An array named numbers with 4 elements is created.

  • Refer to an element of an array with the .(i) syntax, with i being the indexing that starts at 0.  Modify an element with <-.  E.g.:
    numbers.(2) <- 4;;

    The third element of the array numbers is altered to 4.  OCaml returns

    – : unit = ()

    The unit type can only ever have the value ().  It is used for the return value of an operation like setting a mutable field that communicates by side effect rather than by returning a value.

Mutable Record fields and Refs

Records can have some of their fields explicitly declared as mutable, by adding mutable before the name of each field.  E.g.:

type running_sum =
  { mutable sum: float;
    mutable sum_sq: float; (* sum of squares *)
    mutable samples: int;

running_sum is of type record with mutable fields sum, sum_sq, and samples.

Ref is a record type with a single mutable field called contents.  The ref type comes predefined in the standard library, along with its operators:

  • Create a ref with let refName = ref refValue instead of let refName = {contents = refValue}.  E.g.:
    let x = ref 0 ;;

    Creates a ref named x, with 0 in its contents field.

  • Get the contents of a ref with !refName instead of refName.contents.  E.g.:
    !x ;;

    Get the contents of the ref x.

  • Assign value to the contents of a ref with : = instead of <-.  E.g.:
    x := !x + 1 ;;

    Assign the contents of x + 1 to the contents of x.

For and While Loops

Syntax for a for loop:

for StartCounter to EndCounter do
  expressions (*for a sequence of expressions, use ; to separate them *)

Syntax for a while loop:

while expressionEvalutesToTrue do

I’ll stop here before I finish the end of the chapter which is about compiling and running a complete program.



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.