gpt4 book ai didi

ocaml - 使用第一类模块索引集合

转载 作者:行者123 更新时间:2023-12-01 06:50:24 24 4
gpt4 key购买 nike

假设我想索引集合的所有元素并将这个索引存储在 map 中。一个可行的解决方案是扩展 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

现在,内部仿函数的使用有点麻烦,我想使用一个使用第一类模块的实现。到目前为止,我得到了以下信息:
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

我收到以下错误消息
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

我知道我正在使用语法糖并且模块在函数中本地绑定(bind),但是有没有办法使用第一类模块编写函数?

最佳答案

更新后的版本

如果我对您的理解正确,您希望将索引映射算法多态化为映射结构。实际上,您只需要整个 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

关于ocaml - 使用第一类模块索引集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26127691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com