9

我正在 OCaml 中开发一些算法,这些算法需要某些部分是“可插入的”,以便将部分计算留给特定的计算机。

举个例子,假设我有一个这样的签名:

module type Algorithm = sig
    val feed : float -> unit
    val nth : int -> (float -> float)
end

和两个不同的实现将是Alg1Alg2。这个Algorithm模块应该代表各种实现的接口,比如这两个。

现在我需要另一个组件,我们称它为Executor使用Alg1Alg2通过其接口的模块..

阅读函子似乎我应该需要一个函子,它接受一个Algorithm并产生一个ConcreteExecutor我需要的算法的特定实现。所以这Executor是一种对其组件之一进行参数化的模块。

我对吗?这是获得我需要的最佳方式吗?我想知道这样的想法,因为我来自 Java/C++ 背景,所以我习惯于使用接口和抽象类,我需要以正确的方式解决这个函子/模块抽象问题。

获得我想要的东西的正确语法是什么?

提前致谢

4

1 回答 1

4

是的,听起来仿函数就是你想要的。事实上,你可以看看标准库是如何使用仿函数的,因为源代码是可用的。在我的机器上,它位于 /usr/lib/ocaml/3.10.2/。例如,set.mli 包含以下内容:

module type OrderedType =
  sig
    type t
    val compare : t -> t -> int
  end

module type S
  sig
    ...
  end

module Make (Ord : OrderedType) : S with type elt = Ord.t

当您想在 OCaml 中使用集合时,您可以:

module SSet = Set.Make(String);;

因此,使用您的代码,Algorithm 替换 OrderedType,Alg1/Alg2 替换 String,Executor 替换 Make,ConcreteExecutor 是 Executor(Alg1/Alg2) 的结果。您还会注意到 string.mli/ml 没有提及 OrderedType。String 是 OrderedType ,因为它具有类型 t 供函数 compare 使用。您无需明确表示 String 是 OrderedType。

于 2010-08-05T15:33:28.980 回答