OCaml:公开抽象类型的替代方法
OCaml: Alternative ways of exposing abstract type
假设我正在写一个矩阵模块
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模块用于vec
和mat
。我有三个函数,copy_col
、write_col
和 row
,其中 return/write 切片 from/to 矩阵。我想保持模块抽象,所以我没有在签名中指定 'a vec
或 mat
的类型。但是,这隐藏了 'a array
的类型,所以当我使用这些函数时,我无法执行数组操作,例如 a.()
等等。有没有办法在为 MyMat
公开抽象类型的同时仍然为 MAT
保留它?
你想要以下吗?
module MyMat(C:CONSTRAINTS) : (MAT with type dtypes = C.dtypes
and type 'a vec = 'a array) = ...
假设我正在写一个矩阵模块
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模块用于vec
和mat
。我有三个函数,copy_col
、write_col
和 row
,其中 return/write 切片 from/to 矩阵。我想保持模块抽象,所以我没有在签名中指定 'a vec
或 mat
的类型。但是,这隐藏了 'a array
的类型,所以当我使用这些函数时,我无法执行数组操作,例如 a.()
等等。有没有办法在为 MyMat
公开抽象类型的同时仍然为 MAT
保留它?
你想要以下吗?
module MyMat(C:CONSTRAINTS) : (MAT with type dtypes = C.dtypes
and type 'a vec = 'a array) = ...