选择使用命令行参数的ocaml模块 [英] Picking which ocaml module to use with command line parameter
问题描述
在我的代码中,我有 module M = Implementation1
,然后我引用 M
,而不是 Implementation1
。问题是,我必须重新编译我的程序,将 Implementation1
更改为 Implementation2
。我想通过命令行参数来控制使用哪个实现。这是可能的吗?
In my code I've module M = Implementation1
and then I reference M
, instead of Implementation1
. The problem is, I've to recompile my program to change Implementation1
to Implementation2
. I'd like to control which implementation to use from with a command line parameter. Is that possible?
当所有实现共享签名时,情况是否更简单?
Is the situation simpler, when all implementations share signature?
推荐答案
由于这两个实现都是静态的,所以可以使用第一级模块。关于如何构建你的程序有很多不同的可能性,下面是最小化顶层引用单元格和顶层有效语句的一个可能性:
Since both implementation are known statically you can use first class modules. There are quite a few different possibilities on how to structure your program, here's one that minimizes toplevel reference cells and toplevel effectful statements:
module type M = sig
val test : unit -> unit
end
module M1 : M = struct
let test () = Printf.printf "Implementation 1\n%!"
end
module M2 : M = struct
let test () = Printf.printf "Implementation 2\n%!"
end
let test m =
let module M = (val m : M) in
(* If other modules of your program depend on the implementation of
M, functorize them over sig M and instantiate them with M here. *)
M.test ()
let main () =
let exec = Filename.basename Sys.executable_name in
let usage = Printf.sprintf
"Usage: %s [OPTION]...\n\
Program synopsis.\n\
Options:" exec
in
let m = ref (module M1 : M) in
let options = [
"-m1", Arg.Unit (fun () -> m := (module M1 : M)),
" Use implementation 1 (default)";
"-m2", Arg.Unit (fun () -> m := (module M2 : M)),
" Use implementation 2"; ]
in
let anon _ = raise (Arg.Bad "no positional argument supported") in
Arg.parse (Arg.align options) anon usage;
test !m
let () = main ()
这篇关于选择使用命令行参数的ocaml模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!