Search code examples
moduleocaml

Extending OCaml Module


Is there any way to add functions to an already existing module in OCaml?

Specifically, I have some module Loc that tracks locations in a source file. I also have a module called Ast that represents the abstract syntax tree of some code. I want to have the method Loc.of_ast defined in ast.ml, and thus an extension of Loc. Is there any way to do this?

Note: This might be an XY problem. The reason that I'm inclined to believe that such module extensions are possible is because, in Batteries, there are methods such as String.of_int and Int.of_string, which implies these modules are mutually recursive. Surely they aren't all entirely defined in the same file...


Solution

  • What you can do is creating a new module called like an existing module, and include all the functions of the existing module into your new one. The new module shadows the existing one, and you can use all of your newly-defined functions.

    This is how Batteries does it, by the way.

    module List = struct
      include List
    
      let empty = []
    end;;
    
    List.empty;;
    (* - : 'a list = [] *)