How to import OCaml libraries

How to import 3rd party libraries (e.g. not standard libraries) in OCaml?

An answer by Gabriel Scherer on how to import Batteries is just great and answers this question with much information. Although it is for Batteries, the method is general.

The OCaml compiler (or toplevel, etc.) will find with no additional information only the libraries that are distributed along with the compiler (Array, List, etc.). For any other OCaml libraries that you install, you need to give additional information to the compiler as to where this library lies in your filesystem, so that it can find the corresponding modules (compilation units).

If Batteries is installed in your system in /path/foo, you can invoke the toplevel with “ocaml -I /path/foo” to add this path to the “include directories” where OCaml looks for compilation units. You probably don’t know where Batteries is installed, and it is fine because there is an utility for that: ocamlfind. “ocamlfind” is a small and very useful tool (developed by Gerd Stolpmann) that keeps information about where packages are and which libraries to load for each package, and can be used (ocamlfind ocamlc …) to pass the right options to the compiler to use any OCaml package you have installed.

In the toplevel, using ocamlfind requires a bit of in-toplevel scripting, encapsulated in a “topfind” file installed (by ocamlfind) at a place the toplevel knows by default. So the usual workflow to use Batteries (or really any package) from the toplevel is to first load “topfind”, and then use the #require directive (an ocamlfind-specific directive added by topfind) to load the desired package:

#use "topfind";;
#require "batteries";;

from here on, you should be good: using BatList directly will work.

What rixed is suggesting is to put a small bit of magic in your .ocamlinit (a file the toplevel inspects at startup) to automate the (#use “topfind”;;) bit. That’s very convenient in the long run, once you understand what’s happening.

Answered by anonymous.

Leave a Reply

Your email address will not be published. Required fields are marked *