Try to further understanding the interface/module of OCaml

前端 未结 3 1755
眼角桃花
眼角桃花 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)
    

提交回复
热议问题