首页 > 解决方案 > 在 OCaml 中,编写一个适用于 Base.Map 和 Base.Hashtbl 的函数

问题描述

所以我想写一个函数,它把第一类模块作为参数,在 Base.Map 和 Base.Hashtbl 上工作,但我遇到了一个问题。这段代码说明了发生了什么:

module type Len_intf = sig
  type t
  val length : t -> int
end

let show (type a) (module L : Len_intf with type t = a) h =
  printf "len: %d\n" @@ L.length h

let test (type a) h =
  show (module Hashtbl : Len_intf with type t = a) h

尝试编译此结果:

Error: Signature mismatch:
   ...
   Type declarations do not match:
     type ('a, 'b) t = ('a, 'b) Poly.t
   is not included in
     type t
   They have different arities.
   File "test.ml", line 2, characters 2-8:
     Expected declaration
   File "src/hashtbl_intf.ml", line 552, characters 2-17:
     Actual declaration

由于 Hashtbl 和 Map 的类型不同,这甚至可能吗?

标签: ocaml

解决方案


编写一个采用一流模块的函数当然是可能的(你这样做了),它可以这样调用:

let test (type a) (type b) h =
  let module M = struct
      type t = (a,b) Hashtbl.t
      let length = Hashtbl.length
    end in
  show (module M) h

但我认为不可能按照您想要的方式进行。实际上,除了签名已经描述的内容之外,类型等式随后出现。它们无法防止类型数量不匹配。


推荐阅读