标准 ML 中的自引用记录类型

Self referencing record types in Standard ML

我想创建一个记录类型声明,例如

type 'a cx = { foo : string, handler : 'a cx -> 'a cx }

但是这段代码无法编译。

我也试过"mutually recursive type synonym declarations",有点

type 'a cx = { foo : string, handler : 'a hnd }
and 'a hnd = 'a cx -> 'a cx;

没有成功。

在 Haskell 这将是

data Cx a = MkCx { foo :: String, handler :: Cx a -> Cx a }

我如何在 SML 中实现它?

更新

使用相互递归数据类型是可能的

datatype 'a cx = MkCx of string * ('a hnd)
and 'a hnd = MkHnd of 'a cx -> 'a cx;

但这很丑陋,而且没有很好的无序访问记录语法。

我最终将不同的类型打包到单个模块中,即

type 'a cx = { foo : string };
type 'a hnd = 'a cx -> 'a cx
signature CX = sig
    type t
    val cx : t cx
    val handler : t hnd
end

最接近您尝试的是:

datatype 'a cx = CX of { foo : string, handler : 'a hnd }
withtype 'a hnd = 'a cx -> 'a cx

但是,这需要模式匹配才能访问记录。定义访问器函数可能会更方便。

在 SML/NJ 中使用单个构造函数创建代数数据类型对我有用,无需定义多个类型:

datatype 'a cx = CX of { foo : string, handler : 'a cx -> 'a cx }

type 不起作用,因为它只是定义了一个别名(如 C 中的 typedef),不能递归。