ocaml - 在 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 的类型不同,这甚至可能吗?
解决方案
编写一个采用一流模块的函数当然是可能的(你这样做了),它可以这样调用:
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
但我认为不可能按照您想要的方式进行。实际上,除了签名已经描述的内容之外,类型等式随后出现。它们无法防止类型数量不匹配。
推荐阅读
- c - Ncurses,unicode:某些终端上的问题
- android - 如何在 android 中重新构建 HAL?
- c# - 显示大量依赖失败的应用程序洞察力
- python - 将线性回归的结果填充到数据框中
- go - 如何在 Golang 上通过 IPC 为 OpenLDAP 客户端实现 SASL/EXTERNAL?
- regex - python正则表达式从字符串中提取某些单词
- angular - 在图表加载时打开 ng2 折线图上最新点的工具提示
- c# - 如何在 asp.net 中制作带有 url 查询字符串的 cookie
- java - 如何在我的 Java 面板上移动图形元素?
- python-3.x - 有什么方法可以删除从 SQLite3 usign python 创建的数据库的所有内容?