SML不同结构的通用类型

时间:2017-07-04 14:23:22

标签: functional-programming sml functor signature ml

我在标准ML中实现集合。目前它看起来像这样:

signature SET = sig
    type t
    type 'a set
    ...
    val map : ('a -> t) -> 'a set -> t set
end

functor ListSetFn (EQ : sig type t val equal : t * t -> bool end)
        :> SET where type t = EQ.t = struct
    type t = EQ.t
    type 'a set = 'a list
    ...
    fun map f = fromList o (List.map f)
end

我希望map函数能够接受结构SET中的任何集合,理想情况下甚至不会限制来自ListSetFn仿函数的集合。但是,在顶层它只能在由单个结构创建的集合上运行:从它调用的集合,例如:

functor EqListSetFn(eqtype t) :> SET where type t = t = struct
    structure T = ListSetFn(struct type t = t val equal = op= end)
    open T
end

structure IntSet = EqListSetFn(type t = int)
IntSet.map : ('a -> IntSet.t) -> 'a IntSet.set -> IntSet.t IntSet.set

虽然我真的喜欢它像

IntSet.map : ('a -> IntSet.t) -> 'a ArbitrarySet.set -> IntSet.t IntSet.set

有办法吗?我知道它可以在顶级声明,但我想隐藏内部实现,因此使用不透明签名

1 个答案:

答案 0 :(得分:2)

原则上,有两种方法可以执行这样的参数化:

  1. 将函数包装到自己的仿函数中,将其他结构作为参数。

  2. 使函数具有多态性,将相关函数作为单独的参数传递给另一种类型,或作为参数记录。

  3. 我们假设val empty : 'a set val isEmpty : 'a set -> bool val add : 'a * 'a set -> 'a set val remove : 'a * 'a set -> 'a set val pick : 'a set -> 'a 签名包含以下功能:

    functor SetMap (structure S1 : SET; structure S2 : SET) =
    struct
      fun map f s =
        if S1.isEmpty s then S2.empty else
        let val x = S1.pick s
        in S2.add (f x, map f (S2.remove (x, s)))
        end
    end
    

    然后前一个解决方案看起来像这样:

    fun map {isEmpty, pick, remove} {empty, add} f s =
        let
          fun iter s =
            if isEmpty s then empty else
            let val x = pick s
            in add (f x, iter (remove (x, s)))
            end
        in iter s end
    

    对于解决方案2,您需要直接传递所有相关功能,例如作为记录:

    fun map (pack S1 : SET) (pack S2 : SET) f s =
        let
          fun iter s =
            if S1.isEmpty s then S2.empty else
            let val x = S1.pick s
            in S2.add (f x, iter (S2.remove (x, s)))
            end
        in iter s end
    

    FWIW,这对于一流的结构会更好,但SML没有将它们作为标准功能。

    ?
相关问题