OCaml中如何用内部let定义共享私有变量的两个函数?
Your goal is to have two functions (fresh_var and refresh) that share a mutable reference r, while keeping r invisible to the rest of your program. The syntax error in your code comes from incorrect use of and (you don’t need to repeat let after it) and a misstructured scope for the reference. Here are two clean ways to achieve this:
Option 1: Return a Pair of Closures
This approach encapsulates the reference inside a closure and exposes only the two functions you need. The reference r will be completely hidden from outside code:
let fresh_var, refresh = let r = ref 0 in (fun () -> r := !r + 1; Var !r ), (fun () -> r := 0 )
You can then use the functions directly:
fresh_var ();; (* Returns Var 1 *) fresh_var ();; (* Returns Var 2 *) refresh ();; (* Resets the counter to 0 *) fresh_var ();; (* Returns Var 1 again *)
Option 2: Use a Module with Private State
If you prefer to group the functions under a module name, you can create a module where r is only accessible internally. This keeps your code organized and hides the reference from external code:
Basic Module (Simplest)
module VarGenerator = struct let r = ref 0 let fresh_var () = r := !r + 1; Var !r let refresh () = r := 0 end
Use it like this:
VarGenerator.fresh_var ();; (* Var 1 *) VarGenerator.refresh ();; (* Resets counter *)
Truly Private State (With Signature)
For stricter encapsulation, you can define a module signature that only exposes the functions, making r completely invisible outside the module:
module type VAR_GENERATOR = sig val fresh_var : unit -> Var.t (* Adjust Var.t to match your actual type *) val refresh : unit -> unit end module VarGenerator : VAR_GENERATOR = struct let r = ref 0 let fresh_var () = r := !r + 1; Var !r let refresh () = r := 0 end
Why Your Original Code Failed
Your code had two syntax issues:
- You used
and letinstead of justandwhen defining the second function. In OCaml,andis used to define multiple values in the same scope without repeatinglet. - The scope of
rwas only applied to the first function, not both. You need to ensure both functions are defined within the scope whereris declared.
内容的提问来源于stack exchange,提问作者VINT64

