在OCaml中动态切换模块

er0*_*er0 1 ocaml ocaml-core

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

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

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

etc.
Run Code Online (Sandbox Code Playgroud)

不幸的是,在这些之间多路复用的代码是丑陋的:

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
Run Code Online (Sandbox Code Playgroud)

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

Jef*_*eld 5

您可以使用第一类模块.这是一些显示一种可能性的示例代码.

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
Run Code Online (Sandbox Code Playgroud)