0

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.

Dav
  • 17
  • 4

2 Answers2

3

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.

octachron
  • 17,178
  • 2
  • 16
  • 23
-1
(* file_2.ml *)
module File2 = struct
  (* Define your module contents here *)
end
(* file_1.ml *)
open Directory.File2  (* Assuming "Directory" is the name of the parent directory *)

(* Access the contents of the module *)
Dashen
  • 19
  • 1
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Jun 02 '23 at 00:44