In OCaml, are there polymorphic function on generic maps? I.e:
You can have: f : 'a list -> bool as the equivalent to bool f<T> ([T] x)
Can you also have something like: f : ('k,'v) map -> bool as the equivalent to bool f<K,V> (Map<K,V> x)?
If so, what is the correct syntax of the type signature, and how do you implement such a function (I ask since map is an abstract type and the only way to manipulate it is to use functions that you get by calling Map.Make on a concrete type)?
Thanks
It depends on which type of generic map you use, and you have to make a distinction between the two parameters (the type of keys, and the type of values). If you use the Map.Make functor of the default library, you can be generic on the type of values, but the type of keys will be fixed (by the functor instantiation): for a given key module
Key, the maps generated bymodule MyMap = Map.Make(Key)have only one parameter,'v MyMap.t, so you can havef : 'v MyMap.t -> bool.There are other libraries that provide so-called “polymorphic” maps with a type of the form
('k, 'v) pmapthat allow to be polymorphic over both the key and the value type. However, this generally comes at the cost of lesser static guarantees: if you were to change'kin a way that does not preserve the ordering on keys, you would get inconsistent results in a way that cannot be detected at compilation time.Of course, you can implement additional function that work for any key type by enhancing the
Map.Makefunctor itself (code untested):(Remark: If you don’t need a persistent collection (no copy/sharing/backtracking of values) and you don’t care about the worst-case complexity (no use exposed to deny of service attacks by an user), you may also use hashtables, with the Hashtbl module that provides a
('k, 'v) Hashtbl.ttype. But the polymorphism on'kis not really present: you don’t get any function that can make this parameter vary).