문제

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