简体   繁体   English

ocaml记录类型和null

[英]ocaml record type and null

I'm trying to define type like: 我正在尝试定义类型:

type aaa = NULL | 键入aaa = NULL | {a: int; {a:int; b: int};; b:int} ;;

But the compiler does not allow to do it. 但编译器不允许这样做。 I'm not sure of the reason why we can't mix record type with anything else. 我不确定为什么我们不能将记录类型与其他任何东西混合。

I need to match a value if it is the record type or null record and I'm tired of creating dummy record like {a = -999; 我需要匹配一个值,如果它是记录类型或空记录,我厌倦了创建虚拟记录,如{a = -999; b = -999}. b = -999}。

is there a better way ? 有没有更好的办法 ?

The "record" part of the definition has to be done in a separate type. 定义的“记录”部分必须以单独的类型完成。 Then you can wrap that in an "option" type if you want to express "None" or "Some value". 然后,如果要表达“无”或“某些值”,则可以将其包装在“选项”类型中。

type aaa = {a: int; b: int}
type bbb = aaa option

First problem: in the Objective Caml approach, you can't have clean union types without constructors. 第一个问题:在Objective Caml方法中,没有构造函数就不能拥有干净的union类型。 Consider the following conundrum : 考虑以下难题:

type test = Null | {a : int ; b: int }

let value = { a: 0 ; b : 42 } in print_int value.a

The second line is incorrect, because value is of an union type, and might therefore be Null , which has no member a . 第二行是不正确的,因为value是一个联合类型,因此可能是Null ,它没有成员a This would introduce an implicit assumption about the value of an union type, which Objective Caml avoids at all costs. 这将引入关于联合类型值的隐含假设,Objective Caml不惜一切代价避免这种假设。 This means you need a constructor. 这意味着你需要一个构造函数。

But even that would be enough, because then you'd have an anonymous record type: 但即使这样就足够了,因为那时你会有一个匿名记录类型:

type test = Null | Pair of { a : int ; b : int }

match Pair { a : 0 ; b : 42 } with
  | Null -> 0
  | Pair p -> p.a

What would be the type of p here? 这里p的类型是什么? This could certainly be solved by allowing anonymous record types into the language, but it's not a simple addition, as such types are notoriously difficult to handle with a type unification approach and require a lot of additional constructs for support (for instance, the < ; ... > , #type and value :> type constructs for handling objects). 这肯定可以通过允许匿名记录类型进入语言来解决,但它不是一个简单的添加,因为这种类型很难用类型统一方法处理并且需要许多额外的构造来支持(例如, < ; ... > ,# #typevalue :> type用于处理对象的value :> type构造。

Language designers took the easy way out, and required that all record types receive a name. 语言设计者采取了简单的方法,并要求所有记录类型都获得一个名称。 Of course, if you have an exceedingly simple record, you can use a tuple: 当然,如果你有一个非常简单的记录,你可以使用一个元组:

type test = Null | Pair of int * int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM