【问题标题】:Cyclic Map in OCamlOCaml 中的循环映射
【发布时间】:2019-04-09 17:55:02
【问题描述】:

我正在尝试构建递归数据结构,但遇到了一些问题。我目前正在实现一个类型系统,并且我正在尝试实现递归类型。因此,我想使用 OCaml 的类型构造函数来获得可以递归的实际无限类型结构。这是我在错误仍然发生的情况下尽可能减少问题的尝试。

module StringMap = Map.Make(String)

type ty = 
  | TyRecord of (ty StringMap.t)

let rec recursive_ty =
  let rec temp = lazy (
    TyRecord (StringMap.singleton "self" (Lazy.force temp))
  ) in
  Lazy.force temp

并且在执行recursive_ty的表达式时会出现错误Exception: CamlinternalLazy.Undefined

基本上,我正在尝试构造一个循环ty StringMap.t。我希望能够做到这一点不启用-rectypes,特别是因为recursive_ty 的类型不是递归的,它应该只是ty。我知道以下工作正常:

type ty = 
  | TyRecord of (string * ty) list

let rec recursive_ty = TyRecord [("self", recursive_ty)]

但我想使用StringMap 来有效地搜索密钥。任何帮助将不胜感激。

【问题讨论】:

    标签: ocaml lazy-evaluation recursive-datastructures


    【解决方案1】:

    你必须让构造函数变得懒惰,例如,

    type ty = TyRecord of ty StringMap.t Lazy.t
    let rec t = TyRecord (lazy (StringMap.singleton "self" t));;
    

    或者,您可以使用 thunk。

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 2012-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      相关资源
      最近更新 更多