OCaml:暴露抽象类型的替代方法

时间:2015-03-25 04:50:24

标签: ocaml

假设我正在编写矩阵模块

module type MAT = 
sig
  type dtypes
  type 'a vec
  type mat
  val  nan : dtypes

  val make : rows:int -> cols:int -> mat
  val copy_col : mat -> int -> dtypes vec
  val write_col : dtypes vec -> mat -> int -> unit
  val row : mat -> int -> dtypes vec

end;;

具体实施

module MyMat(C:CONSTRAINTS) : (MAT with type dtypes = C.dtypes) = 
struct
  type dtypes = C.dtypes
  type 'a vec = 'a array
  type mat = C.dtypes vec vec
  let nan = C.nan

  let make ~rows ~cols  = Array.make_matrix rows cols nan

  let copy_col mat int =
    let rows = Array.length mat in
    let copy = Array.make rows nan in
    let rec aux n = 
      if (n = rows) then copy else (copy.(n) <- mat.(n).(int); aux (n + 1))
    in aux 0

  let write_col vec mat int =
    let rows = Array.length mat in
    let rec aux n = 
      if (n = rows) then () else (mat.(n).(int) <- vec.(n);aux (n+1))
    in aux 0

  let row m n = m.(n)

end;;   

在具体实现中,Array模块用于vecmat。我有三个函数,copy_colwrite_colrow,它们从/向矩阵返回/写入切片。我想保持模块抽象,所以我没有在签名中指定'a vecmat的类型。但是,这会隐藏'a array的类型,因此当我使用这些函数时,我无法执行a.()等数组操作。有没有办法公开MyMat的抽象类型,同时仍然为MAT保留它?

1 个答案:

答案 0 :(得分:6)

你想要以下吗?

 module MyMat(C:CONSTRAINTS) : (MAT with type dtypes = C.dtypes 
                                    and  type 'a vec = 'a array) = ...