Generalized Folds
The technique we used to derive foldtree works for any OCaml variant type t:
Write a recursive
foldfunction that takes in one argument for each constructor oft.That
foldfunction matches against the constructors, calling itself recursively on any value of typetthat it encounters.Use the appropriate argument of
foldto combine the results of all recursive calls as well as all data not of typetat each constructor.
This technique constructs something called a catamorphism, aka a generalized fold operation. To learn more about catamorphisms, take a course on category theory, such as CS 6117.