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.
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:
type 'a t = unit -> 'a node
and 'a node = Nil | Cons of 'a * 'a tBecause 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.
(* 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_endline5 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 |
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:
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_1002 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:
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:
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 sa=1 b=2 c=3
LAZY
Test yourself
Why can Seq.ints 0 exist even though it is infinite?
- It is stored compressed
- Elements are produced only when requested
- It stops at max_int immediately
- It is an array
What does Seq.unfold f s need f to return?
- A list
Some (value, next_state)orNoneto stop- A boolean
- A sequence
What happens when you iterate a plain Seq.t twice?
- The second time is empty
- The elements are recomputed
- It raises an exception
- The cached values are reused