跨模块键入定义

时间:2010-11-02 09:00:54

标签: module types ocaml

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类型的对象?

2 个答案:

答案 0 :(得分:5)

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

而是将签名ELEMENT定义为:

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

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

答案 1 :(得分:2)

您的示例实际上存在两个问题。第一个是由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... *)