The OCaml repl ("toplevel") has rich printing for any types, user-defined or otherwise. Is it possible to access this functionality outside the toplevel, rather than having to write an entirely custom set of value printers for one's own entire set of types?
In a terminal window, type utop to start the interactive OCaml session, commonly called the toplevel. Press Control-D to exit the toplevel.
In short, the toplevel is OCaml's Read-Eval-Print-Loop (repl) allowing interative use of the OCaml system. You can consider the toplevel an alternative to compiling OCaml into an executable.
1.3 Exiting OCaml To terminate your session with the OCaml interpreter, either use the #quit directive, or type C-d (i.e., control D)1.
This chapter describes the toplevel system for OCaml, that permits interactive use of the OCaml system through a read-eval-print loop (REPL). In this mode, the system repeatedly reads OCaml phrases from the input, then typechecks, compile and evaluate them, then prints the inferred type and result value, if any.
The pretty-printing facility is part of the toplevel library. You'll find the source in toplevel/genprintval.ml
. It's understandable, considering that it needs type information: you can't just throw any value at it, the choice of pretty-printer is based on the type.
If you want to use this code in your program, you'll need to link with the toplevel library (toplevellib.cma
) or compile in genprintval
(which means bringing in enough bits of the type checker to analyse the type, it can get pretty big).
There is a similar facility (but not sharing the code, I think) in the debugger (debugger/printval.ml
and debugger/loadprinter.ml
).
There are third-party libraries that you can directly link against and that provide pretty-printing facilities. Extlib's Std.dump
provides a very crude facility (not based on the type). Deriving by Jeremy Yallop and Jake Donham is another approach. This Caml Weekly News item offers more suggestions.
The OCaml Batteries Included library contains the dump
function in its BatPervasives module . It converts any value to a string and returns it. You can see its source code here. The output will not be identical to the toplevel, because some information is lost at runtime, e.g. abstract data type constructors will become integers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With