typestar

Arrays in OCaml

Fixed-size and mutable: .(i) indexes, <- writes.

(* Arrays are fixed-size and mutable; .(i) indexes, <- writes. *)
let temps = [| 14.5; 13.8; 15.2; 14.1 |]

let () =
  temps.(0) <- 14.9;
  Printf.printf "First reading now %.1f\n" temps.(0);

  let sum = Array.fold_left ( +. ) 0.0 temps in
  Printf.printf "Mean: %.2f C\n" (sum /. float_of_int
    (Array.length temps));

  (* Array.init computes each slot from its index. *)
  let quadrat_ids = Array.init 4 (fun i -> 100 + i) in
  Array.iter (Printf.printf "Q%d ") quadrat_ids;
  print_newline ()

How it works

  1. temps.(0) <- 14.9 writes in place.
  2. Float math spells its operators +. and /..
  3. Array.init computes each slot from its index.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
479
Tokens
121
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 112 seconds.

Type this snippet

Step 2 of 4 in Collections, step 19 of 29 in Language basics.

← Previous Next →

Arrays in other languages