跨模块的类型定义

发布于 2024-09-30 21:52:03 字数 429 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

隔岸观火 2024-10-07 21:52:03

您可以允许程序员在 Semiring 内创建 element_i 类型的值,而不是像您当前所做的那样隐藏该类型的构造函数。

相反,将签名 ELEMENT 定义为:

module type ELEMENT =
sig
    type element_i = N of int | CNN of cnn
end

这使函子 Semiring 期望更多的 Element 参数:而不是任何类型 Element。 element_i,它现在只接受具有这些构造函数的类型。但从好的方面来说,它现在可以应用构造函数来构建这种类型的值,例如 Element.N 12

You can allow the programmer to create values of type element_i inside Semiring by not hiding the constructors of this type, as you are currently doing.

Instead, define the signature ELEMENT as:

module type ELEMENT =
sig
    type element_i = N of int | CNN of cnn
end

This makes your functor Semiring expect more of its Element argument: instead of any type Element.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 instance Element.N 12

子栖 2024-10-07 21:52:03

你的例子实际上有两个问题。第一个是 Pascal 指出的(即,element_i 的构造函数被签名隐藏了)。第二个是函子中的模块 Element 与您上面声明的模块 Element 不同。函子的 Element 参数是“隐藏”Element 的定义,就像函数参数“隐藏”变量一样:

let x = 0

let f = fun x -> (* x here is a different x... *)

module type T = sig (* ... *) end

module M : T = struct (* ... *) end

module F = functor (M : T) -> (* M here is a different M... *)

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 module Element in the functor is not the same as module Element you declared above. The Element argument to the functor is a "hiding" the definition of Element the same way a function parameter would "hide" a variable:

let x = 0

let f = fun x -> (* x here is a different x... *)

module type T = sig (* ... *) end

module M : T = struct (* ... *) end

module F = functor (M : T) -> (* M here is a different M... *)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文