In Real World OCaml, Chapter 9 Functors, it says

Instantiating modules with state

Modules can contain mutable states, and that means that you'll occasionally want to have multiple instantiations of a particular module, each with its own separate and independent mutable state. Functors let you automate the construction of such modules.

The book doesn't have much content on this sub topic. So I ask here.

Can anyone give me an example of instantiating modules with state to demonstrate

  1. How to do that?

  2. When to do that?

有帮助吗?

解决方案

  1. One example: module Make (Arg : S) = struct (** ...Use Arg at will... *) let id = ref 0 let id () = incr id; !id end Each instantiation result Make(Arg) will have it's own id generator.
  2. If you don't feel you need it, just don't do it. In general having state makes reasoning about your code harder.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top