OCaml 顶级输出格式

发布于 2024-10-08 10:57:26 字数 595 浏览 0 评论 0原文

如果我在 OCaml 的顶层执行以下命令:

#require "num";;
open Ratio;;

ratio_of_int 2;;

输出是:

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

这样的格式如何可能? 消息来源告诉我 Ratio.ratio 是一个记录。因此,输出应该更类似于

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

我尝试查看比率输出是否以某种方式硬编码在顶层,但此搜索没有结果。作为 OCaml 的新手,我必须问我是否遗漏了一些重要的东西?在重载字符串化函数的语言中,这并不奇怪,但在 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无法言说的痛 2024-10-15 10:57:26

Findlib 有一个专门用于比率模块的漂亮打印机。它不会打印 (界面不公开记录),而是打印您所看到的内容。如果你想检查一下,请查看 findlib/num_top_printers.ml:

let ratio_printer fmt v =
  Format.fprintf fmt "<ratio %s>" (Ratio.string_of_ratio v)

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)
焚却相思 2024-10-15 10:57:26

顶层有一个指令#install_printer,它采用一个函数来打印任何类型。

例如,您可以重新定义如何打印整数,如下所示:

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

#install_printer 根据作为参数给出的函数类型选择打印机(此处为 Format.formatter -> int ->单位)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文