Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml toplevel output formatting

Tags:

ocaml

If I execute the following in OCaml's toplevel:

#require "num";;
open Ratio;;

ratio_of_int 2;;

The output is:

- : Ratio.ratio = <ratio 2/1>

How's a formatting like this possible? The sources tell me that Ratio.ratio is a record. So the output should be more akin to

{numerator = <big_int 2>; denominator = <big_int 1>; normalized = true}

I tried see if ratio output is somehow hardcoded in toplevel, but this search was fruitless. Being new to OCaml, I must ask if I'm missing something important? In a language that has overloaded stringification funcs this wouldn't be strange, but in OCaml's case I find this behavior quite out of place.

like image 284
Rutherford Avatar asked Dec 15 '10 19:12

Rutherford


2 Answers

Findlib has a pretty printer specifically for the ratio module. Instead of printing out <abstr> (the interface doesn't expose the record), it prints out what you saw. If you want to check it out, look at findlib/num_top_printers.ml:

let ratio_printer fmt v =
  Format.fprintf fmt "<ratio %s>" (Ratio.string_of_ratio v)
like image 96
Niki Yoshiuchi Avatar answered Nov 17 '22 05:11

Niki Yoshiuchi


The toplevel has a directive #install_printer, that takes a function to print any type.

For example, you can redefine how to print integers like this:

let print_integer ppf n = Format.fprintf ppf "Integer(%d)" n
#install_printer print_integer

#install_printer chooses printers depending on the type of the function given as argument (here, Format.formatter -> int -> unit).

like image 28
Fabrice Le Fessant Avatar answered Nov 17 '22 03:11

Fabrice Le Fessant