Reputation: 11
I am trying to pass an AST between modules, I wrote in the Main module the next sentence:
let var = "value" in
.
.
let tree = Parse.parse_tree ~file:input input_text |> M1.f1 |> M2.f2
The point is that in M2.f2
I need to compute a function that receives a parameter from the Main
module.
Is there a way to pass a parameter from one module to another? In a similar way as a "global variable", like in imperative programming? I read that I need to declare a signature in Main.ml
in order to share data types or structures, but I was not able to understand how to use it to pass a variable between modules.
According to this example :
https://ocaml.org/learn/tutorials/modules.html
It is only necessary to reference the var using the name of the module dot the variable.
Upvotes: 0
Views: 436
Reputation: 35210
You can reference a value defined in another module using a qualified name that consists of the module name and the variable name. For example, to reference the variable var
defined in module Main
, you write, Main.var
. Each compilation unit (file) in OCaml, implicitly defines a module with the same name as the file, except that it is capitalized and the extension is thrown away, e.g., if you have a file named foo.ml
it will implicitly define a module Foo
and to reference values defined in this module you need to prefix them with Foo.
By default, all values defined in a module are visible and can be referenced from other modules. You can hide values by defining a signature. If you have an implicit module defined by a file foo.ml
, you can create a signature file foo.mli
that will declare which values are visible.
When you have a complex dune project with multiple folders, it is common that each subfolder defines a different library. Modules inside of the same library can reference each other directly by name. To reference a module in the other library, you should prefix the module name with the name of that library, e.g., Mylib.Foo.var
. Look at the dune
file in the folder that defines the library for the name
field of the library
definition, e.g.,
(library
(name mylib))
In order to access modules of the library mylib
in some other library or program, you also need to add this library to the list of libraries. Open the dune
file in your current folder, and find the corresponding executable
or library
definition and (libraries mylib)
or append mylib
if the libraries
field already exists, e.g.,
(executable hello_word
...
(libraries core mylib))
It is also important to know, that circular dependencies between modules are not permitted in OCaml. For example, if your main application is using library mylib
, the library mylib
can't reference the main
module under any circumstances. So the only way to pass a value from the main module to the library is to pass it as an argument to a function.
Upvotes: 2