Re: Local opening of modules

From: Anton Moscal (msk@post.tepkom.ru)
Date: Tue Nov 10 1998 - 17:04:45 MET


Date: Tue, 10 Nov 1998 19:04:45 +0300 (MSK)
From: Anton Moscal <msk@post.tepkom.ru>
To: John Prevost <j.prevost@cs.cmu.edu>
Subject: Re: Local opening of modules
In-Reply-To: <Pine.LNX.3.95L.981027152714.13499A-100000@naiad.fac.cs.cmu.edu>

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



This archive was generated by hypermail 2b29 : Sun Jan 02 2000 - 11:58:16 MET