user2516663
user2516663

Reputation:

Check 2 sets for inclusion in Scala

abstract class FinSet[T] protected () {
  // given a set other, it returns true iff every element of this is an element of other
  def <=(other:FinSet[T]): Boolean = 
    // ????

That is what I am given so far. I am somewhat confused on how to implement this method. Would I be calling the method like so:

Set(1,2,3).<=(Set(3,2,1)) which should return true

I was wondering if this would work, but it seems too simple:

def <=(other:FinSet[T]): Boolean = if (this == other) true else false

Just looking for some guidance. Thanks.

Upvotes: 2

Views: 1822

Answers (2)

Eddie Jamsession
Eddie Jamsession

Reputation: 1006

& - means intersection, if second set doesn't have elements from first set, the following code would return false.

(thisSet & thatSet) == thisSet

In details this code computes the intersection between this set and another set and checks if elements in this equal to result of the first expression.

see & or intersect(more verbose version) method in Scaladoc

You can also do something like this:

thisSet.forall(x => thatSet contains x)

or less verbose:

thisSet.forall(thatSet contains _)

or like this:

(thisSet ++ thatSet) == thatSet

or maybe like this:

(thatSet -- thisSet).size == (thatSet.size - thisSet.size)

Upvotes: 2

Shadowlands
Shadowlands

Reputation: 15074

Rephrasing the requirement: you want to check if, for all elements of this set, the other set contains the element.

This sounds like the combination of two more primitive functions that you will probably want anyway. So, if you haven't done so already, I would define the methods:

def forall(predicate: T => Boolean): Boolean // Checks that predicate holds for all elements

def contains(elem: T): Boolean // Check that elem is an element of the set

Then the method <= devolves to:

def <=(other: FinSet[T]): Boolean = forall(other.contains)

Upvotes: 1

Related Questions