Search code examples
moduledirectoryocamlocaml-dune

How to include contents of a directory in Ocaml?


How do you include a file's content / module from a directory in Ocaml ?

└── bin
    ├── file_1.ml
    └── directory
        └── file_2.ml

In this example, how do you access file_2 contents in file_1.

I can't figure it out, even though it seems trivial.


Solution

  • You can use include_subdirs to signal to dune that you wish to include subdirectories:

    └── bin
        ├── dune
        ├── file_1.ml
        └── directory
             └── file_2.ml
    

    There two different mode of inclusion, unqualified inclusion

    ; bin/dune file
    (include_subdirs unqualified)
    (executable (name file_1))
    

    that make all modules from subdirectories available in the main directory namespace:

    (* bin/file_1.ml *)
    module F2 = File_2
    

    or qualified inclusion

    ; bin/dune file
    (include_subdirs qualified)
    (executable (name file_1))
    

    that makes modules from subdirectory at path a/b/c available as A.B.C.File_name:

    (* bin/file_1.ml *)
    module F2 = Directory.File_2
    

    Another possibility to bind directory contents with dune is to make the directory a local library:

    └── bin
        ├── dune
        ├── file_1.ml
        └── local_lib_dir
             ├── dune
             └── file_2.ml
    

    where the dune file for bin is

    ; bin/dune
    (executable 
      (name file_1)
      (libraries local_lib)
    )
    

    and the one in the local directory is

    ; bin/local_lib_dir/dune
    (library 
      (name local_lib)
    )
    

    Then one can use the module defined by file_2 with

    (* bin/file_1.ml *)
    module F2 = Local_dir.File_2
    

    inside the bin directory.