Version française
Home     About     Download     Resources     Contact us    
Browse thread
Local opening of modules
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Anton Moscal <msk@p...>
Subject: Re: Local opening of modules
On Tue, 27 Oct 1998, John Prevost wrote:

> This is a question that I found asked back in the logs, but which I
> found no answer to:
> 
> Is there any good reason that Caml doesn't have a mechanism like SML's
> to open a module locally?  For example:
> 
> let open Num in
> let a = num_of_int 2739 in
> let b = num_of_int 234 in
> let bar = a +/ b;;
> 
[...]
> 
> Maybe there's a technical constraint in the way Caml is organized that
> keeps this from being done?
> 

With CamlP4 preprocessor (tool for syntax extension of Ocaml) I got
this effect by the following grammar extension:

====cut====
let (uniq_lid, uniq_uid) = 
    let cnt = ref 0 in
    (incr cnt; fun () -> Printf.sprintf "l_uniq_id_%d" !cnt),
    (incr cnt; fun () -> Printf.sprintf "U_uniq_id_%d" !cnt)

EXTEND
  expr: LEVEL "expr1"
  [[
    "let"; "open"; path = LIST1 UIDENT SEP "."; "in"; e = expr LEVEL "top" ->
    	let temp = uniq_uid () 
    	and res  = uniq_lid ()
    	in
      	<:expr< let module $temp$ = 
      	   struct open $path$; value $lid:res$ = $e$; end in $uid:temp$.$lid:res$
      	>>
  ]];
END
====cut====
After making these changes you can write in your program something like:
====cut====
module M = struct 
	module N = struct let x = 1 end;;
end

let x = let open M.N in x
====cut====

Regards,
Anton