在OCaml中动态切换模块
我在OCaml中有一个由另一个模块参数化的模块,它表示一个数据结构(H=Hashtable,M=Map,L=LossyMap)。我现在希望通过命令行选择此数据结构 我创建主处理模块的方式是:在OCaml中动态切换模块,ocaml,ocaml-core,Ocaml,Ocaml Core,我在OCaml中有一个由另一个模块参数化的模块,它表示一个数据结构(H=Hashtable,M=Map,L=LossyMap)。我现在希望通过命令行选择此数据结构 我创建主处理模块的方式是: module HashSampler = MakeSampler(HashtableMatrix) module MapSampler = MakeSampler(MapMatrix) etc. 不幸的是,在它们之间多路传输的代码很难看: match representation with | "Has
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
有没有更好的方法来防止代码重复?您可以使用一流的模块。下面的一些示例代码显示了一种可能性
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
您可以使用第一类模块。下面的一些示例代码显示了一种可能性
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