在OCaml中动态切换模块

时间:2017-12-03 19:11:03

标签: ocaml ocaml-core

我在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

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

1 个答案:

答案 0 :(得分: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