OCaml中的循环地图

问题描述 投票:1回答:1

我正在尝试构建一个递归数据结构,但我遇到了一些问题。我正在实现一个类型系统,我正在尝试实现递归类型。所以,我希望使用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

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

基本上,我正在尝试构建一个循环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个回答
1
投票

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

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

或者,您可以使用thunk。

© www.soinside.com 2019 - 2024. All rights reserved.