types - OCaml 嵌套结构

标签 types ocaml

我对 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/

相关文章:

c++ - 如何让编译器在没有 C++11 的情况下手动检查数据类型

haskell - 谁发明了代理传递?何时发明的?

types - OCaml 等效类型

OCaml lex : doesn't work at all, 无论如何

ocaml - 从防火墙后面使用 opam

internationalization - OCaml 中的 Gettext 支持

c# - 在没有基础字典结构的 PowerShell 中使用 C# ExpandoObjects(动态)

scala - 具有类型变量的类型模式的用例和示例

integer - ocaml 查看 int 的特定数字

module - OCaml 中的类型共享 - 类型检查器错误