从OCaml中的Map扩展模块

Sof*_*mur 5 ocaml module

我有一个StringMap由仿函数构建的模块,Map.Make给出了一个类型String:

module StringMap = Map.Make(String)
Run Code Online (Sandbox Code Playgroud)

除了提供的普通操作之外Map,我想在这个模块中添加更多定义my_own_function,例如,我可以调用StringMap.my_own_function.有谁知道我应该在哪里定义这种功能及其签名?

nlu*_*oni 9

您可以include在新模块中使用关键字来添加所有相同的功能.这也扩展到OCaml 3.12中签名.

module StringMap =
    struct
        include Map.Make(String)
    end
Run Code Online (Sandbox Code Playgroud)

如果要访问地图的结构,则必须添加一些Obj.magic%identity特殊的外部函数.由于没有进行类型检查,因此必须精确重新定义类型,

module Make (Ord : Map.OrderedType) =
    struct
        include Map.Make(Ord)

        type 'a impl = Empty 
                     | Node of 'a impl * key * 'a * 'a impl * int

        external impl_of_t : 'a t -> 'a impl = "%identity"
        external t_of_impl : 'a impl -> 'a t = "%identity"

        let cardinal map =
            let rec cardinal = function
                | Empty -> 0
                | Node(l,_,_,r,_) -> cardinal l + 1 + cardinal r
            in
            cardinal (impl_of_t map)

    end
Run Code Online (Sandbox Code Playgroud)