Try to further understanding the interface/module of OCaml

前端 未结 3 1696
眼角桃花
眼角桃花 2021-01-28 19:33

I understand in OCaml there are concepts of interfaces and module.

And I understand how to use them now.

However, what I don\'t under

相关标签:
3条回答
  • 2021-01-28 20:18

    The most direct correspondence between your Java example and OCaml is using a functor (what OCaml calls a static function from a module to a module). So suppose you have the following implemented in OCaml:

    module type Map = sig
      (* For simplicity assume any key and value type is allowed *)
      type ('k, 'v) t
    
      val make : unit -> ('k, 'v) t
      val put : ('k, 'v) t -> ~key:'k -> ~value:'v -> unit
    end
    
    module Hashtable : Map = struct ... end
    module HashMap : Map = struct ... end
    

    Then you would write a functor like this:

    module MyFunctor(Map : Map) = struct
      let my_map =
        let map = Map.make () in
        Map.put map ~key ~value;
        map
    end
    

    Then you would instantiate a module using the functor:

    module MyModule = MyFunctor(Hashtable)
    

    And voila, changing the implementation is a one-line diff because both the module implementations conform to the Map signature:

    module MyModule = MyFunctor(HashMap)
    
    0 讨论(0)
  • 2021-01-28 20:21

    Since 3.12.1 OCaml allows this syntax for opening and aliasing modules:

    let foo .... =
      let module HashTable = HashMap in (* magic is here *)
      let h = HashTable.create () in
      ....
    

    So u just need to rename module what you are using where you are using it.

    0 讨论(0)
  • 2021-01-28 20:29

    Here's an example that shows what I think you're asking for:

    # module type HASH = sig type t val hash : t -> int end ;;
    module type HASH = sig type t val hash : t -> int end
    # module I = struct type t = int let hash i = i end ;;
    module I : sig type t = int val hash : 'a -> 'a end
    # module J = struct type t = int end ;;
    module J : sig type t = int end
    # module M : HASH = I ;;
    module M : HASH
    # module N : HASH = J ;;
    Error: Signature mismatch:
           Modules do not match: sig type t = int end is not included in HASH
           The field `hash' is required but not provided
    

    The extra ": HASH" specifies that the module must match the HASH signature (and it also restricts it to that signature).

    Just as a side comment, I believe the OCaml module system is world famous for its expressivity (at least in module system circles). I'm still a beginner at it, but it is worth studying.

    0 讨论(0)
提交回复
热议问题