Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend a module from Map in OCaml

Tags:

module

ocaml

I have a module StringMap built by the functor Map.Make given a type String:

module StringMap = Map.Make(String)

Besides the ordinary operations provided by Map, I would like to add more definitions in this module, for instance, my_own_function, such that I could call StringMap.my_own_function. Does anyone know where I should define this kind of functions and their signature?

like image 409
SoftTimur Avatar asked Dec 28 '11 02:12

SoftTimur


People also ask

How to use map function in OCaml?

In OCaml, we can use the map function with the list library we have already; this function is the part of the list in OCaml so that it can be called on the list. This function takes two arguments as the parameter and bit tricky to understand as well.

What is a functor in OCaml?

A functor is a module that is parametrized by another module, just like a function is a value which is parametrized by other values, the arguments. Basically, it allows to parametrize a type by a value, which is not possible directly in OCaml.

What is an association list in OCaml?

Lots of programming problems require dealing with data organized as key/value pairs. Maybe the simplest way of representing such data in OCaml is an association list, which is simply a list of pairs of keys and values. For example, you could represent a mapping between the 10 digits and their English names as follows:

Is it better to use hash tables or maps in OCaml?

Maps, by virtue of being immutable, are generally the default choice in OCaml. OCaml also has good support for imperative programming, though, and when programming in an imperative idiom, hash tables are often the more natural choice. Programming idioms aside, there are significant performance differences between maps and hash tables.


1 Answers

You can use the include keyword inside a new module to add all the same functions. This was also extended to the signature in OCaml 3.12.

module StringMap =
    struct
        include Map.Make(String)
    end

If you want to access the structure of the map, you'll have to add some Obj.magic or the %identity special external function. The redefinition of the type must be exact since no type checking is happening,

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
like image 191
nlucaroni Avatar answered Sep 27 '22 20:09

nlucaroni