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?
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.
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.
OCaml also supports row polymorphism, which is a form of parametric polymorphism with constraints.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With