0

I might be thinking about the top-level the wrong way. What is the preferred way to maintain a collection of top-level directives as part of a project?

Is there a way to include top-level directives like #install_printer in an OCaml source file so that they are ignored when the program is compiled but executed by the top-level when running?

Ideally, I'd also like the directives to be type checked when the program is compiled even if the directive itself is ignored, e.g.

type 'a with_infinity = Finite of 'a | Infinite

let print_int_with_infinity pp item =
(match item with
    | Infinite -> Format.pp_print_string pp "Infinite"
    | Finite i -> Format.pp_print_int pp i)

(* install printer cannot occur in this context *)
#install_printer print_int_with_infinity
Greg Nisbet
  • 6,710
  • 3
  • 25
  • 65

2 Answers2

2

There is no predefined way of doing that, but you can have a preprocessor remove the directive at compile time.

For typechecking the primitives, the best you can do is to preprocess it to something like

#install_printer some_function

to

let _ = (some_function:Format.formatter -> 'a -> unit)

Pierre Chambart
  • 1,469
  • 12
  • 17
2

A good way to work with the toplevel is to have a .ocamlinit file at the root of the project. This file is loaded when you launch utop or ocaml from the same directory.

It typically looks like this:

#use "topfind";;
#require "this";;
#require "that";;

let _printer = ...;;
#install_printer _printer;;
...

On a related note, if the environment variable OCAMLPATH is set to /path/to/my/project:..., and there's a proper META file in /path/to/my/project/foo, it is then possible to load the project-local foo library and its dependencies using #require "foo".

Martin Jambon
  • 4,629
  • 2
  • 22
  • 28
  • Your advise is – as usual :) – very valuable Martin, this should be the accepted answer! – Michaël Le Barbier Jan 05 '16 at 08:48
  • 1
    Can `.ocamlinit` files source other `.ocamlinit` files? – Greg Nisbet Mar 24 '18 at 05:53
  • @GregoryNisbet it could be useful if `.ocamlinit` files found in subfolders were automatically sourced but it's not how it works. Issues to address would include the order in which those files are loaded and what to do in case of an error. Meanwhile, you can write a sequence of explicit `#use` in your `.ocamlinit`. – Martin Jambon Apr 11 '18 at 17:58