Search code examples
ocaml

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:

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 = M1.t * M2.t = struct
      ...
    end