简体   繁体   中英

SML Multiple Set Intersection Function

I need to write a function in SML that takes an arbitrary number of lists as input and returns the intersection of all the sets given. For example, the function needs to have the following form:

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

I have been able to write the intersection function that takes in two lists as follows:

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

But I am unable to "generalize" this function to take in an arbitrary number of lists as input. I have tried the following:

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

But this is giving me some type mismatch errors and will not work properly. Can anybody help me or give me some tips in order to write this function?

Thank you!

Using this intersection function

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

To do a multiple set intersection, there are 3 cases.

  • If there are no sets, the intersection is [] .

  • If there is one set xs , the intersection is that set.

  • If there are more than two sets, the intersection is the intersect of the first set and the intersection of all the remaining sets.

Putting these four cases together we get:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM