我对 OCaml 很陌生,但我很好奇是否可以进行如下类型声明:
type some_type = {
list_of_things: {
amount: integer;
date: string;
} list;
};;
我确定我做错了什么,但只是想知道。谢谢!
最佳答案
嵌套结构是完全可能的,但是在使用之前需要定义记录类型:
type transaction = {
amount: integer;
date: string;
}
type some_type = {
list_of_things: transaction list;
}
一个原因是 OCaml 类型系统是名义上的(在对象系统和模块系统之外):类型由它们的名称定义,而不是由它们的内容定义。因此列表元素的类型
list_of_things
需要定义,即。命名,某处。也完全可以定义相互递归的记录:
type transaction = {
amount: integer;
date: string;
other: some_type
}
and some_type = {
list_of_things: transaction list;
}
从 OCaml 4.03 开始,还可以在 sum 类型的定义中定义内联记录类型,例如:
type tree = Leaf | Node of { left:tree; right:tree}
但是,内联记录并不完全是一等的,并且不能在其构造函数的上下文之外使用,因为它们缺少专有名称。
关于types - OCaml 嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43461007/