Polymorphic type inside a module (OCaml)

I simply define the Matrix module as follows:

module Matrix =
  struct
    type element
    type t = element array array

    let make (nr: int) (nc: int) (init: element) : t =
      let result = Array.make nr (Array.make nc init) in
      for i = 0 to nr - 1 do
        result.(i) <- Array.make nc init
      done;
      result
  end

And let m = Matrix.make 3 4 0gives me an error Error: This expression has type int but an expression was expected of type Matrix.element. Then I added 'a:

module Matrix =
  struct
    type element = 'a
    type t = element array array

    let make (nr: int) (nc: int) (init: element) : t =
      let result = Array.make nr (Array.make nc init) in
      for i = 0 to nr - 1 do
        result.(i) <- Array.make nc init
      done;
      result
  end

Compiling the module gives an error Error: Unbound type parameter 'a.

Can someone tell me how to determine the type inside my module?

+5
source share
1 answer

Two problems: (1) type variables cannot be called bindings, as you tried with elementand (2) your type tmust have all type variables as parameters if it must be polymorphic, i.e. you either want to write

type 'a t = 'a array array

or you need to turn the module into a functor, where you take elementas a parameter the entire module.

+5
source

All Articles