假设我想索引集合的所有元素并将此索引存储在地图中。一个可行的解决方案是扩展 Set 模块并创建一个内部函子:
module Make(M : Set.S) = struct
include M
module MakeIndexer(MM : Map.S with type key = elt) = struct
let index_set set =
let aux el (ix, acc) =
(ix + 1, MM.add el ix acc)
in
M.fold aux set (0, MM.empty) |> snd
end
end
Run Code Online (Sandbox Code Playgroud)
现在,内部函子的使用有点麻烦,我想使用使用一流模块的实现。到目前为止,我得到了以下信息:
module Make(M : Set.S) = struct
include M
let index_map (module MM : Map.S with type key = elt) set =
let aux el (ix, acc) =
(ix + 1, MM.add el ix acc)
in
M.fold aux set (0, MM.empty) |> snd
end
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息
Characters 156-191:
M.fold aux set (0, MM.empty) |> snd
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type int MM.t
but an expression was expected of type int MM.t
The type constructor MM.t would escape its scope
Run Code Online (Sandbox Code Playgroud)
我知道我正在使用语法糖并且模块在函数中本地绑定,但是有没有办法使用第一类模块编写函数?
如果我理解正确,您希望使索引映射算法对映射结构具有多态性。事实上,您只需要整套 Map 操作中的两个内容:初始值和加法运算符。所以你可以将它们作为参数传递给你的函数。
module Make(T : Set.OrderedType) = struct
module Set = Set.Make(T)
let index_map (set : Set.t) (map : 'm) add : 'm =
let aux el (ix, acc) =
(ix + 1, add el ix acc) in
Set.fold aux set (0, map) |> snd
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
81 次 |
最近记录: |