3 ms·
Ocaml, being in the ML family, makes heavy use of Algebraic Datatypes. For example, from https://www.ocaml.org/manual/5.1/api/List.html https://www.ocaml.org/ma
by chriswarbo 2y ago
Ocaml, being in the ML family, makes heavy use of Algebraic Datatypes. For example, from https://www.ocaml.org/manual/5.1/api/List.html https://www.ocaml.org/manual/5.1/api/List.html we can encode lists like this:
type 'a t = 'a list =
| []
| (::) of 'a * 'a list
In other words, values of type `'a list` are either `[]` (the empty list, like `nil` in Lisp), or `(::)` applied to two arguments (prepending an element to a list, like `cons` in Lisp). We can tell whether a particular value is one of the other by storing a bit of information, called a "tag". We can later branch on that bit to perform pattern-matching.
In constrast, the "tagless" encoding seems closer to Church-encoding. A Church-encoded list is a function which accepts two arguments, say `x` and `y`:
- An "empty list" will return `x` as-is.
- A non-empty list will call `y` with two arguments: one argument is the first element of the list, and the other argument is the result of calling the tail of the list with `x` and `y`.
Such functions have many other names, like "elimination forms", or "induction/recursion schemes", etc.
The linked page shows an example of implementing lists using the tagless approach, which like Church encoding but collects together the required parts in a record. I reckon a similar approach could be implemented via modules, but am not too experienced in Ocaml to know how easy/awkward that would be.