Ocaml-多态打印和类型丢失 [英] Ocaml - polymorphic print and type losing

查看:98
本文介绍了Ocaml-多态打印和类型丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OCaml中有一系列功能,例如print_int,print_endline和Printf.我不能做这样的事情:

There is series of functions like print_int, print_endline and Printf in OCaml. I can't do something like:

let n = 10 in
print n;; (* And I haven't to change `print` in case type of `n` changed *)

这是Java,C#,Python等中的多态打印.相反,我们有类似C的类型,类型由程序员明确定义.因此,我认为OCaml在编译过程中会丢失类型信息,而在运行时则不会,对吧?这就是为什么我们也需要mli文件的原因吗?

That is polymorphic print like in Java, C#, Python and others. Instead, we have C-like with type explicitly defined by programmer. So I think that OCaml losing type information during compilation and doesn't have it at runtime, right? And this is the reason why we need mli files also?

编辑:我很疲倦地编写诸如* print_listi *,* print_list_tuple2i *等功能.我该如何做得更好?

I'm tired to write function like *print_listi*, *print_list_tuple2i* and so on. How can I do it better?

推荐答案

您是对的:OCaml在运行时会丢弃类型,因此无法区分10是真正的int还是第10个0元变体构造函数.构造函数名称都不可用,因此无法打印数据.

You are right: OCaml throws away types at run time and therefore no way to distinguish your 10 is really an int or 10th 0-ary variant constructor. Constructor names are neither available, so it is impossible to print data.

此外,OCaml的多态性是参数化的.您不能定义因类型而异的功能.

Moreover OCaml's polymorphism is parametric. You cannot define functions which work differently depending on types.

此问题的部分解决方法是使用CamlP4自动为数据类型生成打印机功能.但是,您仍然不能拥有适用于所有事物的多用魔幻"印刷品.您必须手动组合打印机,例如print_list(print_option print_int).

One partial workaround of this is to use CamlP4 to auto generate printer functions for data types. But still you cannot have " polymagical" print which works for everything. You have to combine printers by hand, like print_list (print_option print_int).

几年前,我已经将OCaml扩展为具有这种多态打印(和其他不错的功能).它称为GCaml.但维护时间不长.

I have extended OCaml to have such polymorphic print (and other nice things) years ago. It's called GCaml. But not maintained for long.

mli文件与此无关.它们用于编写模块签名,用于为模块用户隐藏更简单的接口的实现.

mli files do not relate with this. They are for writing module signatures, for hiding implementations for simpler i nterfaces for module users.

这篇关于Ocaml-多态打印和类型丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆