Tutorial
OCaml's New Proposed "include functor" Syntax | OCaml Unboxed
- Jane Street is developing "include functor," a feature for the OCaml compiler currently in development with plans to upstream it to the mainstream compiler.
- The feature addresses the difficulty of completing partially written modules where specific implementations (like
mapanditer) follow repetitive patterns across different contexts. - The speaker illustrates the problem using a
Mappablemodule type containing:- A generic data type
twith a key. - Functions
mapanditer. - Functions
mapIanditerIthat additionally accept the key.
- A generic data type
- In a standard scenario, instantiating
Mappablewith an array requires manually implementingmapanditer. - When implementing a reverse array iteration (
rev array map):- The key and type
tremain identical to the forward iteration. mapIanditerIare rewritten to process elements from end to start.mapIhandles the empty array case and initializes the result using the last element before iterating backward.
- The key and type
- A manual workaround using a standard functor (
make map iter) was shown to be cumbersome:- The
Mappabletype must be split into a "minimal" part (excludingmap/iter) and the rest. - To apply the functor, the target module must be wrapped in an extra intermediate module.
- The resulting code requires manual reordering of includes and explicit inclusion of the original module
mto avoid leaking the intermediate signature.
- The
- "Include functor" resolves these issues by:
- Allowing a module to directly include the result of a functor applied to the module's own preceding definitions, eliminating the need for an intermediate wrapper module.
- Automatically treating the current module context as the input argument to the functor.
- Simplifying code for
rev array mapto a singleinclude functor make map iterstatement.
- The feature supports inclusion within module types, though this usage case is noted as less common.
- A working compiler version implementing this feature is available for testing via a link provided in the video description.