typestar

Lists and cons in OCaml

Immutable and linked: :: builds, @ appends, patterns split.

(* Lists are immutable and linked; :: builds, @ appends. *)
let morning = ["north"; "ledge"]
let all_pools = "cove" :: morning @ ["shelf"]

let () =
  print_endline (String.concat " -> " all_pools);
  Printf.printf "First: %s of %d\n"
    (List.hd all_pools) (List.length all_pools);
  (* head :: tail patterns split a list in a match. *)
  match all_pools with
  | first :: rest ->
      Printf.printf "%s leads %d others\n" first (List.length rest)
  | [] -> print_endline "no pools at all"

How it works

  1. "cove" :: morning @ ["shelf"] builds without copying the tail.
  2. List.hd and List.length read the shape.
  3. first :: rest destructures head and tail in a match.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
470
Tokens
95
Three-star pace
65 tpm

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

Type this snippet

Step 1 of 4 in Lists, step 11 of 29 in Language basics.

← Previous Next →

Lists and cons in other languages