Module 定义一个数值多态模块
我想定义一个可以支持Module 定义一个数值多态模块,module,ocaml,Module,Ocaml,我想定义一个可以支持int、int64和float的模块。比如说, module Matrix = struct type 'a t = 'a array array (* add point-wise 2 matrices with same dimension *) let add (m: 'a t) (n: 'a t): 'a t = ... end add的实现需要操作员plus,对于int,+。对于float和Int64。对于Int64添
int
、int64
和float
的模块。比如说,
module Matrix =
struct
type 'a t = 'a array array
(* add point-wise 2 matrices with same dimension *)
let add (m: 'a t) (n: 'a t): 'a t =
...
end
add
的实现需要操作员plus
,对于int
,+。
对于float
和Int64。对于Int64
添加。所以我不能写任何一个,否则,Matrix
的类型就不再是多态的了
谁能告诉我你是如何解决这个问题的
我现在的一个想法是把矩阵
变成一个函子:
module type NUM_TYPE =
sig
type t
val add: t -> t -> t
end
module Matrix =
functor (Elt: NUM_TYPE)
struct
type element = Elt.t
type t = element array array
(* add point-wise 2 matrices with same dimension *)
let add (m: t) (n: t): t =
...
end
然后我必须定义以下数值模块:
module MyInt =
(struct
type t = int
let add (a: t) (b: t): t = a + b
end: NUM_TYPE)
module MyFloat = ...
module MyInt64 = ...
module MatInt = Matrix(MyInt)
module MatFloat = Matrix(MyFloat)
module MatInt64 = Matrix(MyInt64)
通过这种方法,我发现定义MyInt
、MyFloat
和MyInt64
,尤其是它们自己的add
函数非常繁琐。有人有任何改进的想法吗?你可以这样把每一个都写在一行中:
module MatInt = Matrix(struct type t = int let add = (+) end)
我不认为您可以在OCaml中做得更好(看看这篇博文:)。这将是TypeClass的一个很好的用法。如果您同意使用语言扩展,可以查看此项目: