Arrays in OCaml

In OCaml, an array is a mutable sequence of elements of the same type. Arrays have a fixed length, which is determined when they are created. Let’s explore how to work with arrays in OCaml.

(* We use the Printf module for formatted printing *)
open Printf

let () =
  (* Here we create an array 'a' that will hold exactly 5 integers.
     By default, an array is initialized with 0s for integers. *)
  let a = Array.make 5 0 in
  printf "emp: %s\n" (Array.to_string string_of_int a);

  (* We can set a value at an index using Array.set,
     and get a value with Array.get *)
  Array.set a 4 100;
  printf "set: %s\n" (Array.to_string string_of_int a);
  printf "get: %d\n" (Array.get a 4);

  (* The Array.length function returns the length of an array *)
  printf "len: %d\n" (Array.length a);

  (* Use this syntax to declare and initialize an array in one line *)
  let b = [|1; 2; 3; 4; 5|] in
  printf "dcl: %s\n" (Array.to_string string_of_int b);

  (* OCaml doesn't have a direct equivalent to Go's ... syntax for arrays,
     but we can use list syntax and convert to an array *)
  let b = Array.of_list [1; 2; 3; 4; 5] in
  printf "dcl: %s\n" (Array.to_string string_of_int b);

  (* OCaml doesn't have a direct equivalent to Go's index-based initialization,
     but we can create a function to achieve a similar result *)
  let make_array_with_indices arr =
    Array.mapi (fun i x -> if i = 0 then 100 else if i = 3 then 400 else if i = 4 then 500 else 0) arr
  in
  let b = make_array_with_indices (Array.make 5 0) in
  printf "idx: %s\n" (Array.to_string string_of_int b);

  (* Array types are one-dimensional, but you can create arrays of arrays
     to build multi-dimensional data structures *)
  let twoD = Array.make_matrix 2 3 0 in
  for i = 0 to 1 do
    for j = 0 to 2 do
      twoD.(i).(j) <- i + j
    done
  done;
  printf "2d: %s\n" (Array.to_string (Array.to_string string_of_int) twoD);

  (* You can create and initialize multi-dimensional arrays at once too *)
  let twoD = [|
    [|1; 2; 3|];
    [|1; 2; 3|]
  |] in
  printf "2d: %s\n" (Array.to_string (Array.to_string string_of_int) twoD)

Note that arrays in OCaml are printed in the form [|v1; v2; v3; ...|] when using the Array.to_string function.

To run this program, save it as arrays.ml and compile it with:

$ ocamlc -o arrays arrays.ml
$ ./arrays
emp: [|0; 0; 0; 0; 0|]
set: [|0; 0; 0; 0; 100|]
get: 100
len: 5
dcl: [|1; 2; 3; 4; 5|]
dcl: [|1; 2; 3; 4; 5|]
idx: [|100; 0; 0; 400; 500|]
2d: [|[|0; 1; 2|]; [|1; 2; 3|]|]
2d: [|[|1; 2; 3|]; [|1; 2; 3|]|]

This example demonstrates how to create, initialize, and manipulate arrays in OCaml, including multi-dimensional arrays. While the syntax differs from other languages, the concepts remain similar.