跨模块的类型定义
module type ELEMENT =
sig
type element_i
end
module Element:ELEMENT =
struct
type element_i = N of int | CNN of cnn
end
module type SEMIRING =
functor (E:ELEMENT)->
sig
type elements
end
module Semiring:SEMIRING =
functor(Element:ELEMENT) ->
struct
let zero = (Element.element_i 0) (*ERROR: Unbounded Value; Same with N 0*)
end
如何在 Semiring 模块中创建 element_i 类型的对象?
module type ELEMENT =
sig
type element_i
end
module Element:ELEMENT =
struct
type element_i = N of int | CNN of cnn
end
module type SEMIRING =
functor (E:ELEMENT)->
sig
type elements
end
module Semiring:SEMIRING =
functor(Element:ELEMENT) ->
struct
let zero = (Element.element_i 0) (*ERROR: Unbounded Value; Same with N 0*)
end
How can I create objects of the type element_i inside Semiring module here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以允许程序员在
Semiring
内创建element_i
类型的值,而不是像您当前所做的那样隐藏该类型的构造函数。相反,将签名
ELEMENT
定义为:这使函子
Semiring
期望更多的Element
参数:而不是任何类型Element。 element_i
,它现在只接受具有这些构造函数的类型。但从好的方面来说,它现在可以应用构造函数来构建这种类型的值,例如Element.N 12
You can allow the programmer to create values of type
element_i
insideSemiring
by not hiding the constructors of this type, as you are currently doing.Instead, define the signature
ELEMENT
as:This makes your functor
Semiring
expect more of itsElement
argument: instead of any typeElement.element_i
, it now only accepts a type with exactly these constructors. But on the plus side it can now apply the constructors to build values of this type, for instanceElement.N 12
你的例子实际上有两个问题。第一个是 Pascal 指出的(即,
element_i
的构造函数被签名隐藏了)。第二个是函子中的模块Element
与您上面声明的模块Element
不同。函子的Element
参数是“隐藏”Element
的定义,就像函数参数“隐藏”变量一样:There's actually two problems with your example. The first is pointed out by Pascal (i.e., the constructors of
element_i
are hidden by the signature). The second is that the moduleElement
in the functor is not the same as moduleElement
you declared above. TheElement
argument to the functor is a "hiding" the definition ofElement
the same way a function parameter would "hide" a variable: