模块内部的多晶型(OCaml)

时间:2012-01-15 12:40:29

标签: types module polymorphism ocaml

我只需按如下方式定义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

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

模块的编译给出了错误Error: Unbound type parameter 'a

有人能告诉我如何定义模块内部的类型吗?

1 个答案:

答案 0 :(得分:5)

两个问题:(1)类型变量无法通过绑定命名,就像您尝试使用element一样,以及(2)您的类型t需要将所有类型变量作为参数(如果它是应该是多态的。也就是说,你要么想写

type 'a t = 'a array array

或者您必须将模块转换为仿函数,并将element作为整个模块的参数。