【发布时间】:2017-12-07 16:42:09
【问题描述】:
我正在编写一个仿函数来实现标准 ML 中的集合。由于集合不允许重复并且我不希望它被限制为相等类型,因此它的声明如下:
signature SET = sig
type t
type 'a set
val add : t -> t set -> t set
...
end
functor ListSet (EQ : sig type t val equal : t * t -> bool end) :> SET = struct
type t = EQ.t
type 'a set = 'a list
fun add x s = ...
...
end
我使用:>,因此列表操作不能用于集合,隐藏内部实现并允许更改表示(例如,更改为 BST)
不过,这也隐藏了type t,因此函数add 在这样使用时会报错:
structure IntSet = ListSet (struct type t = int val equal = op= end);
val s0 = IntSet.empty
val s1 = IntSet.add 0 s0
Function: IntSet.add : IntSet.t -> IntSet.t IntSet.set -> IntSet.t IntSet.set
Argument: 0 : int
Reason:
Can't unify int (*In Basis*) with
IntSet.t (*Created from applying functor ListEqSet*)
(Different type constructors)
有没有办法隐藏实现但以某种方式暴露类型 t?还是有更好的方法来实现集合?
附:我不能有相等类型的主要原因是允许集合集合,虽然我可以保持列表排序并定义eqtype 'a set,但它增加了不必要的复杂性。
【问题讨论】:
标签: functional-programming sml functor signature ml