newsfilter.io
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 map and iter) follow repetitive patterns across different contexts.
  • The speaker illustrates the problem using a Mappable module type containing:
    • A generic data type t with a key.
    • Functions map and iter.
    • Functions mapI and iterI that additionally accept the key.
  • In a standard scenario, instantiating Mappable with an array requires manually implementing map and iter.
  • When implementing a reverse array iteration (rev array map):
    • The key and type t remain identical to the forward iteration.
    • mapI and iterI are rewritten to process elements from end to start.
    • mapI handles the empty array case and initializes the result using the last element before iterating backward.
  • A manual workaround using a standard functor (make map iter) was shown to be cumbersome:
    • The Mappable type must be split into a "minimal" part (excluding map/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 m to avoid leaking the intermediate signature.
  • "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 map to a single include functor make map iter statement.
  • 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.
OCaml's New Proposed "include functor" Syntax | OCaml Unboxed — Summary