typestar

Seq in OCaml

The lazy sequence: infinite until something pulls.

(* Seq is the lazy sequence: infinite until something pulls. *)
let tides = Seq.ints 1 |> Seq.map (fun n -> n * 6 mod 24)

let () =
  tides
  |> Seq.take 4
  |> Seq.iter (Printf.printf "Low tide near %02d:00\n");

  (* unfold grows a sequence from state until None stops it. *)
  let draining = Seq.unfold
      (fun cm -> if cm <= 0 then None else Some (cm, cm - 15)) 60 in
  draining
  |> Seq.map string_of_int
  |> List.of_seq
  |> String.concat " > "
  |> Printf.printf "Pool draining: %s cm\n"

How it works

  1. Seq.ints 1 never ends; Seq.take 4 decides what runs.
  2. Seq.unfold grows from state until None stops it.
  3. List.of_seq materializes when the laziness is done.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
472
Tokens
111
Three-star pace
60 tpm

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

Type this snippet

Step 3 of 4 in Collections, step 20 of 29 in Language basics.

← Previous Next →