List 多集交函数

List 多集交函数,list,functional-programming,intersection,sml,List,Functional Programming,Intersection,Sml,我需要在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::interse

我需要在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])
但这给了我一些类型不匹配错误,无法正常工作。有人能帮我写这个函数或者给我一些提示吗


谢谢大家!

使用此相交函数

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,则交点就是该集合

如果有两个以上的集合,则交点是第一个集合与所有剩余集合的交点

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

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

谢谢你的帮助,这很有道理。有没有一种方法来编写intersect函数,以消除exists函数,而使用模式匹配?List.exists fun y=>x=y ys只是使用标准库的x,y的成员。您可以使用模式匹配自己实现该功能。我认为您不需要第三种情况。