How does one print any type?

There is no such facility in OCaml. OCaml is not an interpreted language with a dynamic type system. When a program is compiled all types are erased, so it is impossible in runtime to reflect a value to its type. And yes, as you’ve already pointed out, when you interact with OCaml using interactive toplevel there is some generic printing facility, but this is a very special case because you’re not really running a program, but interactively compile it.

So, you have to accept this fact and learn how to program in OCaml using OCaml ways of doing things. First of all, learn how to use the Format.printf function. This is a generic function that takes the format specification and arguments and prints them, e.g.,

open Format

let () = 
  printf "Hello, %s world\n%!" "cruel";
  printf "Hello, %d times!\n%!" 42

As you can see, the special format specifiers, like %s or %d specify the type of an argument. So %d expects one argument of type int, and %s expects one of string, there is also %c for char , %b for bool and so on.

There is also a generic %a specifier, which expects not one argument, but two – a function, that will tell how to print the argument, and the argument itself. It is used to print values of abstract types, hence the name %a. There is a convention, that modules that define abstract types also provide a function called pp which specifies how this value should be printed, e.g.,

let () = printf "Hello, abstract student %a\n%!" Student.pp s

Where the Student module might be defined as

struct Student : sig 
   type t 
   val create : string -> int -> t
   val pp : Format.formatter -> t -> unit
end = struct 
   type t = {name : string; cls : int}
   let create name cls  = {name; cls}
   let pp ppf {name; cls} = 
      Format.fprintf ppf "%s of %d" name cls
end

That is roughly how we print everything in OCaml :slight_smile:

16 Likes