首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在OCaml中,编写一个适用于Base.Map和Base.Hashtbl的函数

在OCaml中,编写一个适用于Base.Map和Base.Hashtbl的函数
EN

Stack Overflow用户
提问于 2020-06-01 06:47:56
回答 1查看 56关注 0票数 0

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

代码语言:javascript
复制
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

尝试编译此代码将导致:

代码语言:javascript
复制
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的不同类型,这是可能的吗?

EN

回答 1

Stack Overflow用户

发布于 2020-06-02 18:10:43

编写一个接受一级模块的函数当然是可能的(您已经这样做了),并且可以这样调用它:

代码语言:javascript
复制
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

但我认为不可能按你想要的方式去做。实际上,除了签名已经描述的内容之外,类型相等也是随后出现的。它们不能防止类型不匹配。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62123397

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档