I am new to OCaml and am trying to “import” an OPAM package I installed.
I am not sure how this is done.
I have a few lines of code in my ~/.ocamlinit which I am assuming allow me to run the following code: #require “ez_file”;;
FileString.read_file “data.json”;;
This works perfectly on the REPL but I am not able to make it run as a project.
I have a project set up using:
VSCode WSL on Ubuntu 20.04 on Windows 10
dune set up
When I run a simple hello world code, this set up is working fine.
However when i use the code I used in REPL (given above) I get an error on the “#”
I am really confused as to how do I use this library in my project?
Welcome to OCaml ! It sounds like this might be a problem with your dune file. When building your app.exe with dune you need to also specify the libraries it uses in a dune file. Something like the following should work:
(executable
(name app)
(libraries ez_file))
This tells dune that app.ml will be the entry-point for your code and that you will be using the ez_file library.
And in your app.ml file
let () =
print_string (FileString.read_file "data.json")
So your directory will look like:
.
|-- app.ml
|-- data.json
`-- dune
From the ez_file documentation we can see the exposed modules. FileString is one of them hence we don’t need to open EzFile (note there is no underscore unlike the library name). The #require directive is used in the REPL to include those packages so you can use them as you described but it is not part of the OCaml syntax, it is for the REPL.
Note as well you’ll need to run dune build or similar to generate the appropriate files to makes this work. Also make sure you select the correct opam switch and maybe even restart the language server.
To do this open the command palette (on Mac this is cmd + p) and type > OCaml: select... to select the opam switch and > OCaml: Restart Language Server to do that.
Hopefully with all this information you will be able to get it up and running