【问题标题】:SML Multiple Set Intersection FunctionSML 多集交集函数
【发布时间】:2017-09-04 06:10:49
【问题描述】:

我需要在 SML 中编写一个函数,该函数将任意数量的列表作为输入并返回所有给定集合的交集。例如,函数需要有如下形式:

multiSetIntersection([s1,s2,s3,s4]) = (Intersection of s1,s2,s3,s4)

我已经能够编写以下两个列表的交集函数:

    fun intersec([], y) = []
      | intersec(x::xs, y) =
        if memberOf(x,y) then x::intersec(xs,y)
        else intersec(xs,y)

但是我无法“概括”这个函数来接收任意数量的列表作为输入。我尝试了以下方法:

    fun multiSetIntersection([]) = []
      | multiSetIntersection((x::xs)::y) =
            if memberOf(x,y) then x::multiSetIntersection([xs,y])
            else multiSetIntersection([xs,y])

但这给了我一些类型不匹配的错误,并且无法正常工作。任何人都可以帮助我或给我一些提示来编写这个函数吗?

谢谢!

【问题讨论】:

    标签: list functional-programming intersection sml


    【解决方案1】:

    使用这个交集函数

    fun intersect ([], _) = []
    | intersect (x::xs, ys) =
      if List.exists (fn y => x = y) ys
      then x :: intersect (xs, ys)
      else intersect (xs, ys)
    

    做多集交集,有3种情况。

    • 如果没有集合,则交集为[]

    • 如果有一个集合xs,则交集就是那个集合。

    • 如果有两个以上的集合,则交集是第一个集合的intersect 和其余所有集合的交集。

    将这四个案例放在一起,我们得到:

      fun intersects [] = []
      | intersects [xs] = xs
      | intersects (xs::xss) = intersect (xs, intersects xss);;
    

    【讨论】:

    • 感谢您的帮助,这是有道理的。有没有办法以消除 exists() 函数的方式编写“相交”函数,而是使用模式匹配?
    • List.exists (fun y => x = y) ys 只是 memberOf (x, y) 使用标准库。您可以使用模式匹配自己实现该功能。
    • 我认为你不需要第三种情况。
    猜你喜欢
    • 2016-06-11
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多