Sof*_*mur 5 polymorphism ocaml types module
我只是定义一个Matrix模块如下:
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
Run Code Online (Sandbox Code Playgroud)
并let m = Matrix.make 3 4 0给我一个错误Error: This expression has type int but an expression was expected of type Matrix.element.然后我补充说'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
Run Code Online (Sandbox Code Playgroud)
模块的编译给出了错误Error: Unbound type parameter 'a.
谁能告诉我如何定义模块内部的类型?
两个问题:(1)类型变量不能通过绑定命名,就像你试过的那样element,(2)你的类型t需要将所有类型变量作为参数,如果它应该是多态的.也就是说,你要么想写
type 'a t = 'a array array
Run Code Online (Sandbox Code Playgroud)
或者您必须将模块转换为仿函数,并将其element作为整个模块的参数.