typestar

Folds in OCaml

fold_left threads an accumulator of any shape.

(* fold_left threads an accumulator; it can be any shape. *)
let depths_cm = [40; 65; 25; 90; 55]

let total = List.fold_left ( + ) 0 depths_cm

(* A tuple accumulator tracks deepest and count in one pass. *)
let deepest, sampled =
  List.fold_left
    (fun (best, n) d -> (max best d, n + 1))
    (0, 0) depths_cm

let () =
  Printf.printf "Total depth walked: %d cm\n" total;
  Printf.printf "Deepest of %d pools: %d cm\n" sampled deepest;
  (* fold_right associates the other way; order shows in strings. *)
  let names = List.fold_right (fun d acc -> string_of_int d :: acc)
      depths_cm [] in
  print_endline (String.concat "/" names)

How it works

  1. List.fold_left ( + ) 0 is the canonical sum.
  2. A tuple accumulator tracks deepest and count in one pass.
  3. fold_right associates the other way — order shows in output.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
616
Tokens
118
Three-star pace
60 tpm

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

Type this snippet

Step 3 of 4 in Lists, step 13 of 29 in Language basics.

← Previous Next →

Folds in other languages