Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cartesian Product of modules

Trying to create a functor which would, given 2 modules of signature Set.OrderedType, create a module of signature Set.OrderedType representing objects of type the product of the two types, (Not really clear sorry) and being therefore able to compare said objects (using for instance the lexicographic order), to be able to use this module for Set

But, when I try to do this

module CartesianProduct2 (M1 : Set.OrderedType) (M2 : Set.OrderedType) :
  Set.OrderedType = struct
  type t = M1.t * M2.t

  let compare (a : t) (b : t) : int =
    match (a, b) with
    | (c, d), (e, f) ->
        if M1.compare c e <> 0 then M1.compare c e else M2.compare d f
end

(*A module to handle char*char *)
module Char2 = CartesianProduct2 (Char) (Char)

The code works fine except from the fact that OCaml does not recognize Char2.t as char*char 🙁 meaning that when I try to compare two char*char instances like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Char2.compare ('a', 'b') ('c', 'd')

OCaml raises an error, saying: This expression has type ‘a * ‘b but an expression was expected of type Char2.t

>Solution :

Modules in OCaml are structurally typed, so adding a module type annotation will only remove information. That is, by adding the return type annotation Set.OrderedType you force t to be abstract, hence the error.

The easiest way of fixing this is therefore to simply remove the annotation. The actual type will then be inferred. However, if you actually do need to remove some information from the module signature, you can also specify what the type of t should actually be using the with type construct:

module CartesianProduct2 (M1 : Set.OrderedType) (M2 : Set.OrderedType) :
  Set.OrderedType with type t = MN1.t * M2.t = struct
  ...
end
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading