Version française
Home     About     Download     Resources     Contact us    
Browse thread
Rephrasing of dynamic module selection problem
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Virgile Prevosto <virgile.prevosto@m...>
Subject: Re: [Caml-list] Rephrasing of dynamic module selection problem
Hello,

Le lun 20 fév 2006 17:54:32 CET, Nathan Cooprider a écrit:
> [coop@ender example]$ cat main.ml
> module Hello1 = struct
>   #include "hello1.ml"
> end ;;
> module Hello2 = struct
>   #include "hello2.ml"
> end ;;

This is not needed: the file hello1.ml implicitely defines a module Hello1
(same for hello2.ml and Hello2).

> (* This works . . . *)
> module H = Hello1
> (* But I would like this to be something like this instead:
> let parameter = 1
> module H =
>   match parameter with
>     1 -> Hello1
>   | _ -> Hello2
>  *)

This might not completely solve your problem, but the following camlp4
extension allows you to use the following expression:
choose_module H = 
match parameter with
 1 -> Hello1
| _ -> Hello2
in 
let argument = 42 in 
let main () = H.print (H.of_int argument) in
main ();;

Note that the scope of H is the expression following the first "in" and
not all the remaining of main.ml. This might be an issue, but it could
be solved by the use of functors (e.g.:
module type Hello = sig ... end
module F (H: Hello) = struct ... end
...
choose_module H = ... in
let module FH = F(H) in ... ;;
)

-------- choose_module.ml4 ----------
(* compile it with
ocamlc -c -I +camlp4 -pp "camlp4o pa_extend.cmo q_MLast.cmo -impl" -impl
choose_modules.ml4

to use it,
ocamlc -c -pp "camlp4o choose_modules.cmo" main.ml 
Note that by default, camlp4 doesn't search for extension in the current
directory, so that you may have to add a "-I ." directive
*) 
open Pcaml;;

let make_one_choice a mod_expr exp =
  let _loc = Lexing.dummy_pos, Lexing.dummy_pos in 
    <:expr<let module $uid:a$ = $mod_expr$ in $exp$>> 

let choices = Grammar.Entry.create Pcaml.gram "choices" 

EXTEND
   expr: [[
            "choose_module"; a = UIDENT; "="; "match" ; cond = expr;
            "with"; OPT "|"; l = LIST1 choices SEP "|";  
            "in"; e = expr -> 
              let new_l = List.map 
                            (fun (patt,optwhen,expr) -> 
                               (patt,optwhen, make_one_choice a expr e)) l
              in  <:expr< match $cond$ with [$list:new_l$] >> ]];
  choices: [[ p=patt; w = OPT ["when"; e = expr -> e]; "->"; 
              m = module_expr -> (p,w,m)
            ]];
END
-------------------------------------
-- 
E tutto per oggi, a la prossima volta
Virgile