选择使用命令行参数的ocaml模块

pbp*_*pbp 4 ocaml functional-programming module

在我的代码我module M = Implementation1然后我引用M,而不是Implementation1.问题是,我要重新编译我的程序以Implementation1改为Implementation2.我想通过命令行参数控制要使用的实现.那可能吗?

当所有实现共享签名时,情况是否更简单?

Dan*_*zli 7

由于两个实现都是静态已知的,因此您可以使用第一类模块.关于如何构建程序有很多不同的可能性,这里有一个最小化顶层参考单元和最有效的语句:

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