Question

The Ocaml interpreter is able to display (print) any kind of value. For example, if a function returns an array, it can print an array. Also, this works even with custom types. For example, if I do :

type dummy = DUMMY of int * string;; let x = DUMMY(1, "s");;

Then x;; prints on this on the screen :

-: dummy = DUMMY(1, "s")

My question is, how can I access this functionality? For example, if I'm debugging some code and want to print some non-standard object (i.e, something other than int, string etc), then how can I do that using the function the interpreter uses, without having to create a separate print function for everything?

Was it helpful?

Solution

OCaml is a typeful language but it throws away its type information such as constructor names at runtime of standalone programs. Therefore you cannot have the general value printer which require such type information.

OCaml toplevel or REPL, which you referred as interpreter, is an exception: it keeps types in memory.

For now, if you want to print values a little easier you can auto-generate them using CamlP4 extensions such as "deriving". But it does not provide one generic printer but provides a printer for each type automatically. You still need to compose them like print_list print_dummy for printing values of dummy list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top