Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic type inside a module (OCaml)

I just define a 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 0 gives 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

The compilation of the module gives an error Error: Unbound type parameter 'a.

Could anyone tell me how to define the type inside of my module?

like image 647
SoftTimur Avatar asked Jan 15 '12 12:01

SoftTimur


People also ask

Does OCaml allow polymorphic functions?

In OCaml, higher-order and polymorphic functions are powerful tools for code reuse. Higher-order functions are those functions that take other functions as arguments or return functions as results, while polymorphic functions are functions that act over values with many different types.

What is a polymorphic data type?

A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (e.g. a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made.

Does OCaml support parametric polymorphism?

OCaml also supports row polymorphism, which is a form of parametric polymorphism with constraints.

What is type A in OCaml?

The type 'a is a type variable, and stands for any given type. The reason why sort can apply to lists of any type is that the comparisons (=, <=, etc.) are polymorphic in OCaml: they operate between any two values of the same type. This makes sort itself polymorphic over all list types.


1 Answers

Two problems: (1) type variables cannot be named by a binding, like you tried with element, and (2) your type t needs to have all type variables as parameters if it is supposed to be polymorphic. That is, you either want to write

type 'a t = 'a array array

or you have to turn the module into a functor, where you take element as a parameter of the entire module.

like image 119
Andreas Rossberg Avatar answered Sep 25 '22 02:09

Andreas Rossberg