为何OCaml中record类型的声明不是type synonym?
OCaml中Tuple与Record的类型行为差异
1. Tuple的类型别名特性
当我们为tuple类型声明多个类型别名时,这些别名指向的是同一类型:
type a = int * int * int type b = int * int * int type c = int * int * int
a、b和c属于完全相同的类型,它们只是int * int * int的类型别名,不需要也不应该有数据构造器——因为本质上它们就是同一个类型的不同名称。
2. Record的类型行为差异
但record类型的表现截然不同:
type a = { name : string } type b = { name : string } type c = { name : string }
这里的a、b和c是不同的类型,可以通过以下代码验证:
({ name = "something" } : a) = ({ name = "something" } : b) ;; // 错误提示:This expression has type b but an expression was expected of type a
这种行为类似Haskell中的newtype,且无需定义数据构造器。OCaml中的record是原生概念,拥有自身独立的类型标识。
3. 疑问
既然tuple和record同属OCaml的复合类型,为何二者在类型别名的表现上存在这种不一致性?虽然可以通过module解决record结构重复的问题,但我想了解这种设计差异的根本原因。
内容的提问来源于stack exchange,提问作者kwonryul
相关产品推荐
相关产品推荐

