ML:是否可以在 SML 中创建结构列表?

ML: Is it possible to create a list of structures in SML?

我是 ML/Haskell 的初学者,我正在尝试创建一个结构列表。 实际上,我正在 Urweb (functional web programming language, a lot of features from ML and Haskell.) I am trying to create an interface to Tinymce(开源富文本编辑器,它包含打印等所有插件,link)中开发一个 Web 应用程序。因此,为了管理所有插件,我以结构的形式进行组合,我需要一个数据结构来保存所有结构(在我的例子中是插件),并且在最后阶段可以用来初始化我的编辑器。

例如:

val plugins = [print, link, img];

和列表plugins内的元素如print是一个结构:

structure print = struct
  type t = string
  .
  .
end

我怎样才能做到这一点?

一般的答案是不,你不能创建一个列表 结构,签名和仿函数也是如此

但是;如果您的插件系统是以一种方式构建的,其中每个插件的入口类型和出口类型在所有插件中都是相同的,您可以构建一种结构闭包并将其嵌入到函数中。

然后您可以使用函子来构建您的插件系统的功能

我们从每个 "plugin" 的界面开始。

signature DANCER =
sig
    type t;

    val dancer : t
    val tired : t -> bool
    val dance : t -> t;
end

后面是我们的应用程序与插件交互的接口。

datatype exhaustion = Exhausted;

signature DANCING_MANIA =
sig
  val dance : unit -> exhaustion;
end

上面DANCING_MANIA签名的实现, 接受 DANCER,并隐藏 plugins/structures

之间的差异
functor Dancer (D : DANCER) : DANCING_MANIA =
struct

  fun dance() =
    let fun until_exhaustion (dancer) =
         if not (D.tired dancer)
            then until_exhaustion(D.dance(dancer))
            else Exhausted;
     in until_exhaustion(D.dancer) end
end

最后我们可以实现一些插件,并将它们放在一个列表中。

structure Tony :> DANCER =
struct
  type t = int;

  val dancer = 5;

  fun tired x = x <= 0;
  fun dance x = (print "tony dance!\n"; x - 1);
end

structure Annette :> DANCER =
struct
  type t = real;

  val dancer = 1.0;

  fun tired x = x <= 0.0;
  fun dance x = (print "annette dance!\n"; x - 0.2);
end
structure TonyDance = Dancer(Tony);
structure AnnetteDance = Dancer(Annette);

val dancers = [TonyDance.dance, AnnetteDance.dance];

fun danceOff (x::xs) = let val _ = x(); in danceOff(xs) end
  | danceOff ([]) = ();
val _ = danceOff(dancers);

所以,我们的想法是,虽然您无法创建结构列表, 你可以创建一个事物列表,每个事物都包含不同的结构, 只要暴露的类型是统一的。