TExcelTAD
Home › OCaml › OCaml Arrays

OCaml Arrays

An array is a fixed-size, mutable sequence of elements of the same type, stored contiguously in memory. Unlike lists, arrays give O(1) access to any element by index. Array literals use [| ... |]:

ocaml · try it yourself
let () =
  let temps = [| 12.5; 15.0; 9.75; 18.25 |] in
  Printf.printf "length %d\n" (Array.length temps);
  Printf.printf "first %.2f, last %.2f\n" temps.(0) temps.(Array.length temps - 1);
  temps.(2) <- 10.0;                         (* arrays are mutable *)
  Array.iter (Printf.printf "%.2f ") temps;
  print_newline ()
length 4
first 12.50, last 18.25
12.50 15.00 10.00 18.25 

Read with a.(i), write with a.(i) <- v. Indices run from 0 to length - 1; anything else raises Invalid_argument "index out of bounds".

Creating arrays

ocaml · try it yourself
let show a = "[|" ^ String.concat "; " (Array.to_list (Array.map string_of_int a)) ^ "|]"

let () =
  print_endline (show (Array.make 5 0));
  print_endline (show (Array.init 6 (fun i -> i * i)));
  print_endline (show (Array.of_list [ 3; 1; 2 ]));
  print_endline (show (Array.append [| 1; 2 |] [| 3 |]));
  print_endline (show (Array.sub [| 10; 20; 30; 40; 50 |] 1 3))
[|0; 0; 0; 0; 0|]
[|0; 1; 4; 9; 16; 25|]
[|3; 1; 2|]
[|1; 2; 3|]
[|20; 30; 40|]

The Array module

The Array module mirrors much of List: map, iter, iteri, fold_left, exists, for_all, mem, to_list, plus array-specific functions like blit, fill and in-place sort:

ocaml · try it yourself
let () =
  let scores = [| 71; 94; 58; 88; 66 |] in
  let total = Array.fold_left ( + ) 0 scores in
  Printf.printf "total %d, mean %.1f\n" total (float total /. float (Array.length scores));
  Printf.printf "any fail: %b\n" (Array.exists (fun s -> s < 60) scores);
  let sorted = Array.copy scores in
  Array.sort compare sorted;                 (* sorts in place, returns unit *)
  Array.iteri (fun i s -> Printf.printf "#%d:%d " (i + 1) s) sorted;
  print_newline ();
  Printf.printf "original still: %d %d\n" scores.(0) scores.(1)
total 377, mean 75.4
any fail: true
#1:58 #2:66 #3:71 #4:88 #5:94 
original still: 71 94

Array.sort modifies the array, so we sorted a copy.

Matrices

A 2-D grid is an array of arrays. Use Array.make_matrix or Array.init (not Array.make n (Array.make m 0), see the warning below):

ocaml · try it yourself
let () =
  let rows = 3 and cols = 4 in
  let grid = Array.make_matrix rows cols 0 in
  for r = 0 to rows - 1 do
    for c = 0 to cols - 1 do
      grid.(r).(c) <- (r + 1) * (c + 1)
    done
  done;
  Array.iter
    (fun row -> print_endline (String.concat " " (Array.to_list (Array.map (Printf.sprintf "%2d") row))))
    grid
 1  2  3  4
 2  4  6  8
 3  6  9 12

Warning: Array.make 3 (Array.make 4 0) creates one inner array and puts it in all three slots. Changing grid.(0).(0) would change every row! Array.make copies the reference to the value, not the value itself.

ocaml · try it yourself
let () =
  let shared = Array.make 3 (Array.make 2 0) in
  shared.(0).(0) <- 7;
  Array.iter (fun row -> Printf.printf "%d " row.(0)) shared;
  print_newline ()
7 7 7 

Arrays versus lists

List Array
Mutable no yes
Size grows by consing at the front fixed at creation
Index access O(n) O(1)
Add to front O(1) O(n) (copy)
Pattern matching natural (x :: rest) only fixed-size patterns [| a; b |]
Typical use functional processing, recursion numeric work, lookup tables, buffers

For a growable array, OCaml 5.2 added the Dynarray module (Dynarray.create, add_last, get, length). For large numeric data, Float.Array stores floats unboxed.

Test yourself

How do you read element 2 of array a?

  1. a[2]
  2. a.[2]
  3. a.(2)
  4. List.nth a 2

What does Array.sort compare a return?

  1. A new sorted array
  2. unit, because it sorts a in place
  3. A sorted list
  4. The number of swaps

Why is Array.make 3 (Array.make 3 0) a trap for a 3x3 grid?

  1. It does not compile
  2. All rows are the same inner array
  3. It creates a 9-element flat array
  4. It is too slow