开发者

OCaml toplevel output formatting

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.


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)


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜