Scala set function

I don't think it's possible without iterating through all the integers. For a pseudo-proof, look at the desired type:

def subset: (a: Set, b: Set): Boolean

Somehow, we've got to produce a Boolean when all we have to work with are sets (a, b) of type Int => Boolean, and integer equality (Int, Int) => Boolean. From these primitives, the only way to get a Boolean value is to start with Int values. Since we don't have any specific Int's in our hands, the only option is to iterate through all of them.

If we had a magical oracle, isEmpty: Set => Boolean, the story would be different.

A final option is to encode "false" as the empty set and "true" as anything else, thus changing the desired type to:

def subset: (a: Set, b: Set): Set

With this encoding, logical "or" corresponds to the set union operation, but I don't know that logical "and" or "not" can be defined easily.


We have

Set A = 
    Returns the intersection of the two given sets,
    the set of all elements that are both in `s` and `t`.

Set B = 
    Returns the subset of `s` for which `p` holds.

Isn't Set A is equivalent to Set B

def filter(s: Set, p: Int => Boolean): Set = intersect(s, p)