OCaml 顶级输出格式
如果我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Findlib 有一个专门用于比率模块的漂亮打印机。它不会打印
(界面不公开记录),而是打印您所看到的内容。如果你想检查一下,请查看 findlib/num_top_printers.ml: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:顶层有一个指令
#install_printer
,它采用一个函数来打印任何类型。例如,您可以重新定义如何打印整数,如下所示:
#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:
#install_printer
chooses printers depending on the type of the function given as argument (here,Format.formatter -> int -> unit
).