TExcelTAD
Home › OCaml › OCaml Sequences

OCaml Sequences

A sequence ('a Seq.t) is a lazy list: its elements are computed only when someone asks for them. This makes it possible to describe very long or even infinite streams of values, and to chain transformations without building intermediate lists.

ocaml · try it yourself
let () =
  let naturals = Seq.ints 1 in                     (* 1, 2, 3, ... forever *)
  let first_squares = naturals |> Seq.map (fun n -> n * n) |> Seq.take 6 in
  Seq.iter (Printf.printf "%d ") first_squares;
  print_newline ()
1 4 9 16 25 36 

Seq.ints 1 is infinite, but nothing is computed until Seq.iter pulls elements, and Seq.take 6 stops after six.

What a sequence is

A sequence is a function that, when called with (), produces either Nil (the end) or Cons (x, rest) where rest is another sequence:

ocaml
type 'a t = unit -> 'a node
and 'a node = Nil | Cons of 'a * 'a t

Because the rest is a function, it is evaluated only on demand. You can build sequences by hand with this definition, but the Seq module's constructors are usually easier.

ocaml · try it yourself
(* a hand-written sequence: count down from n to 1 *)
let rec countdown n () = if n = 0 then Seq.Nil else Seq.Cons (n, countdown (n - 1))

let () =
  countdown 5 |> List.of_seq |> List.map string_of_int |> String.concat " " |> print_endline
5 4 3 2 1

Building sequences

Function Produces
Seq.empty, Seq.return x no elements / one element
Seq.ints n n, n+1, n+2, ... (infinite)
Seq.init n f f 0, ..., f (n-1)
Seq.repeat x, Seq.cycle s x forever / s repeated forever
Seq.iterate f x x, f x, f (f x), ...
Seq.unfold f state generate from a state: f returns Some (value, next_state) or None
List.to_seq, Array.to_seq, String.to_seq, Hashtbl.to_seq from a collection
ocaml · try it yourself
let show s = s |> Seq.map string_of_int |> List.of_seq |> String.concat " "

let () =
  print_endline (show (Seq.iterate (fun x -> x * 2) 1 |> Seq.take 8));
  (* Fibonacci numbers from a state (a, b) *)
  let fibs = Seq.unfold (fun (a, b) -> Some (a, (b, a + b))) (0, 1) in
  print_endline (show (Seq.take 12 fibs));
  (* digits of a number, least significant first *)
  let digits n = Seq.unfold (fun k -> if k = 0 then None else Some (k mod 10, k / 10)) n in
  print_endline (show (digits 90210));
  print_endline (show (Seq.cycle (List.to_seq [ 1; 2; 3 ]) |> Seq.take 7))
1 2 4 8 16 32 64 128
0 1 1 2 3 5 8 13 21 34 55 89
0 1 2 0 9
1 2 3 1 2 3 1

Transforming and consuming

Seq has the familiar map, filter, filter_map, take, drop, take_while, zip, fold_left and more. A pipeline only does as much work as the consumer needs:

ocaml · try it yourself
let is_prime n =
  let rec check d = d * d > n || (n mod d <> 0 && check (d + 1)) in
  n >= 2 && check 2

let () =
  let primes = Seq.ints 2 |> Seq.filter is_prime in
  let first_ten = primes |> Seq.take 10 |> List.of_seq in
  print_endline (String.concat " " (List.map string_of_int first_ten));
  let first_over_1000 = primes |> Seq.drop_while (fun p -> p <= 1000) |> Seq.uncons in
  (match first_over_1000 with Some (p, _) -> Printf.printf "first prime > 1000: %d\n" p | None -> ());
  let sum_below_100 = primes |> Seq.take_while (fun p -> p < 100) |> Seq.fold_left ( + ) 0 in
  Printf.printf "sum of primes < 100: %d\n" sum_below_100
2 3 5 7 11 13 17 19 23 29
first prime > 1000: 1009
sum of primes < 100: 1060

Laziness you can observe

Each element is computed when it is requested, and a plain Seq.t recomputes it every time it is traversed:

ocaml · try it yourself
let () =
  let noisy = Seq.ints 1 |> Seq.map (fun n -> Printf.printf "(computing %d) " n; n * 10) in
  let first_two = Seq.take 2 noisy in
  print_endline "nothing computed yet";
  Seq.iter (Printf.printf "got %d ") first_two;
  print_newline ();
  Seq.iter (Printf.printf "again %d ") first_two;
  print_newline ()
nothing computed yet
(computing 1) got 10 (computing 2) got 20 
(computing 1) again 10 (computing 2) again 20 

If the elements are expensive and you need them several times, convert to a list (List.of_seq) or use Seq.memoize.

Converting between collections

Sequences are also the standard "bridge" between collection types:

ocaml · try it yourself
module SMap = Map.Make (String)

let () =
  let pairs = [ ("b", 2); ("a", 1); ("c", 3) ] in
  let m = SMap.of_seq (List.to_seq pairs) in
  let arr = Array.of_seq (SMap.to_seq m) in
  Array.iter (fun (k, v) -> Printf.printf "%s=%d " k v) arr;
  print_newline ();
  let s = String.of_seq (Seq.map Char.uppercase_ascii (String.to_seq "lazy")) in
  print_endline s
a=1 b=2 c=3 
LAZY

Test yourself

Why can Seq.ints 0 exist even though it is infinite?

  1. It is stored compressed
  2. Elements are produced only when requested
  3. It stops at max_int immediately
  4. It is an array

What does Seq.unfold f s need f to return?

  1. A list
  2. Some (value, next_state) or None to stop
  3. A boolean
  4. A sequence

What happens when you iterate a plain Seq.t twice?

  1. The second time is empty
  2. The elements are recomputed
  3. It raises an exception
  4. The cached values are reused