Wednesday, August 24, 2022

[FIXED] How can one specify the value type for an OCaml map

Issue

I want to declare ahead of time the value type for a map type.

The functor Map.Make returns a Map.S with two type definitions:

type key
type !+'a t

Type 'a appears to be the type of values in the map. For example, this is the function for adding a key (of type key and value of type 'a:

    val add: key -> 'a -> 'a t -> 'a t

One can write the key type like this:

module type M = Map.S with type key = string

But I couldn't figure out how to specify the value type. This isn't valid syntax:

module type M = Map.S with type key = string  and 'a = int

Solution

One way to look at this is that you're trying to impose monomorphism in the wrong place. The essence of Map.S is that it's polymorphic in the element type.

You can easily define a type for maps from string keys to int values:

# module M = Map.Make(String);;
. . .
# type string_int_mod = int M.t;;
type string_int_mod = int M.t

# let f (m: string_int_mod) s i = M.add s i m;;
val f : string_int_mod -> M.key -> int -> int M.t = <fun>

In many cases, the polymorphism inferred by OCaml is clearer than specifically ascribed types. At least in my opinion. The types inferred by OCaml tell you what the code is really doing and where it has degrees of freedom.



Answered By - Jeffrey Scofield
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.