【问题标题】:SML functor expose a type without exposing implementation (implementing sets)SML 函子公开类型而不公开实现(实现集)
【发布时间】: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


    【解决方案1】:

    您需要有时称为半透明签名归属,即隐藏一些类型并公开其他类型:

    functor ListSet (Eq : EQ) :> SET where type t = Eq.t = ...
    

    【讨论】:

      【解决方案2】:

      您必须使用类型细化公开类型 t

      functor ListSet (Eq : sig type t val equal : t * t -> bool end) :> SET where type t = Eq.t =
      struct
        ...
      end
      

      这等效于签名SET 的扩展,其中t 类型被透明地指定为

      type t = Eq.t
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-17
        • 2013-03-12
        • 2022-12-05
        • 1970-01-01
        • 2010-11-14
        • 1970-01-01
        • 1970-01-01
        • 2014-04-07
        相关资源
        最近更新 更多