Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Map / define a type which actually is a Map in OCaml?

I am going to practicing using Map in Ocaml.

I found that the usage of Map is quite different from List, Array, etc.

I understand it is applying functor which I haven't learnt yet. but it is fine.


Here is my IntMap

module IntMap = Map.Make(struct type t = int let compare = compare end)

So, now I can use IntMap to add by IntMap.add x y map, etc, right?


I have a few questions:

  1. How do I control the type of value in the map?
  2. If I want a alias type for my IntMap, what should I do? I can do type 'a my_type = 'a list, but how to do for map?
  3. I find that IntMap is like List and both of them are actually modules. But List has a type of list, what about the map?
like image 632
Jackson Tale Avatar asked Jan 24 '26 00:01

Jackson Tale


1 Answers

Q:

How do I control the type of value in the map?

You don't (need to), 'a IntMap.t is a parametrized type that contains values of type 'a. A single module IntMap can therefore be used for map from ints to ints, from ints to bools, ints to functions... (of course a single map value can only contain bindings of a single type). Furthermore there is no reason to try to constrain the type of IntMap.empty, just as there is no reason to force [] to be of any type other than 'a list.

Q:

If I want a alias type for my IntMap, what should I do? I can do type 'a my_type = 'a list, but how to do for map?

This way:

type 'a imap = 'a IntMap.t

Q:

I find that IntMap is like List and both of them are actually modules. But List has a type of list, what about the map?

This is Intmap.t.

like image 80
gasche Avatar answered Jan 26 '26 23:01

gasche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!