为什么我不能访问我的结构的内部ORD_SET结构?

时间:2013-04-29 00:22:05

标签: scope structure sml smlnj

我编写的这个练习旨在帮助我理解标准ML中的签名,结构和仿函数。我似乎无法让它发挥作用。仅供参考,我正在使用

Standard ML of New Jersey v110.75 [built: Sun Jan 20 21:55:21 2013]

对于“可以计算幅度的对象”,我有以下ML签名:

signature MAG_OBJ =
sig
   type object
   val mag : object -> int
end

如果我想给出一个“有大小的int集合”的结构,我可能有一个用于标准库的ORD_SET签名的有序int的结构,如下所示:

structure OrderedInt : ORD_KEY =
struct
   type ord_key = int
   val compare = Int.compare
end

然后我可以创建一个仿函数给我一个具有所需类型和属性的结构:

functor MakeMagSet(structure ELT : ORD_KEY) : MAG_OBJ =
struct
   structure Set : ORD_SET = RedBlackSetFn(ELT)
   type object = Set.set
   val mag = Set.numItems
end

到目前为止一切顺利(至少所有内容都编译)。现在我为上面创建的OrderedInt结构创建了一个结构实例:

structure IntMagSet = MakeMagSet(structure ELT = OrderedInt)

但是当我尝试使用它(创建一个集合并计算其大小)时,我收到一个错误:

val X = IntMagSet.Set.addList(IntMagSet.Set.empty, [0,1,2,3,4,5,6,7,8,9])

给出错误:

Error: unbound structure: Set in path IntMagSet.Set.empty.addList

根据我的理解,使用以下方式不透明地签署签名:>使得它无法访问签名中未明确定义的任何结构内部,但我透明地将MAG_OBJ归于其中,因此我应该能够访问Set结构,对吧?我在这里缺少什么?

[编辑]

甚至重写函子以专门将我想要的函数绑定到struct也不行:

functor MakeMagSet(structure ELT: ORD_KEY) : MAG_OBJ =
struct
   structure Set : ORD_SET = RedBlackSetFn(ELT)
   type object = Set.set
   val mag = Set.numItems
   val empty = Set.empty
   val addList = Set.addList
end

尝试访问“empty”和“addList”会产生未绑定的变量错误。

另一方面,尝试在struct之外显式定义Set结构并使用它的函数在调用mag时会出现类型错误:

Error: operator and operand don't agree [tycon mismatch]
  operator domain: IntMagSet.object
  operand:         Set.set
  in expression:
    IntMagSet.mag X

1 个答案:

答案 0 :(得分:1)

我认为这是因为您明确表示MakeMagSet的类型会生成MAG_OBJ,其签名不包含Set。如果你已经摆脱了: MAG_OBJMAG_OBJ包含ORD_SET,那么它就可以了。