在 OCaml 中动态切换模块

Switching between modules dynamically in OCaml

我在 OCaml 中有一个模块被另一个模块参数化,它代表一个数据结构(H = Hashtable,M = Map,L = LossyMap)。我现在想让这个数据结构通过命令行来选择。

我创建主处理模块的方式是:

module HashSampler = MakeSampler(HashtableMatrix)
module MapSampler = MakeSampler(MapMatrix)

etc.

不幸的是,在它们之间多路复用的代码很丑陋:

match representation with
| "Hashtable" ->
       let matrix = HashSampler.create () in
           HashSampler.process_file matrix file
| "Map" -> 
       let matrix = MapSampler.create () in
           MapSampler.process_file matrix file

是否有更好的方法来防止代码重复?

您可以先使用 class 个模块。这是显示一种可能性的一些示例代码。

module type Sampler = sig
    type t
    val create : unit -> t
    val process_file : t -> string -> unit
end
module HashSampler : Sampler = struct
    type t = unit
    let create () = ()
    let process_file () file = ()
end
module MapSampler : Sampler = struct
    type t = unit
    let create () = ()
    let process_file () file = ()
end

let choose_sampler : string -> (module Sampler) = function
    | "Hashtable" -> (module HashSampler)
    | "Map" -> (module MapSampler)

let process representation file =
    let (module M) = choose_sampler representation in
    let matrix = M.create () in M.process_file matrix file