The Hyperpessimist

The grandest failure.

OCaml Library Development in the REPL

Maybe like me, you develop a lot by exploration, in the REPL/Toplevel/UTop. Lately I’ve been writing a library but was very annoyed by the fact that testing the functions I wrote in the REPL worked so bad. With the help of #ocaml I found a workaround that is kinda passable. Passing it on, in case you or future me will need this knowledge later.

I’ll explain the basic setup: my code is managed by OASIS and ocamlbuild puts the compiled code into _build/src, so all cmo, cma files etc. are there. I have dependencies on the Uri, Yojson and Cohttp.lwt libraries.

First you have to actually build your code, so it is available in _build/src, I do this via ocaml setup.ml -build. Depends on your build system, of course.

  1. Start utop
  2. #require "uri";; to load the Uri module, the other steps are similar. When you miss one require, OCaml will let you know by saying “Error: Reference to undefined global Foobar”
  3. #require "yojson";;
  4. #require "cohttp.lwt";;
  5. #directory "_build/src";; This step is important! I left it out and could load my module, but not use any function from it.
  6. #load "mymodule.cma";; This loads your code. Now you can use it in the REPL. Or it throws some error, in which case you might need to #require some more packages and retry.

Yes, not a very pretty way, but it works for development. My biggest hope for future OCaml development is not more features but first and foremost an easier way to deal with the compiler, for now (4.01) we’re stuck with this.