Scala set.contains implementation
type Set = Int => Boolean
/**
* Indicates whether a set contains a given element.
*/
def contains(s: Set, elem: Int): Boolean = s(elem)
Why does this feature contains
work?
I do not understand. How does the operator ()
return true
/ false
about the existence of this element in the set?
source to share
Taking this piece by piece, the type alias on the first line means that we can rewrite the second line like this:
def contains(s: Int => Boolean, elem: Int): Boolean = s(elem)
But it A => B
's just syntactic sugar for Function1[A, B]
, so we can do more rewriting:
def contains(s: Function1[Int, Boolean], elem: Int): Boolean = s(elem)
s(elem)
is also syntactic sugar - whenever you "apply" a value to a value in this way, Scala allocates it to s.apply(elem)
:
def contains(s: Function1[Int, Boolean], elem: Int): Boolean = s.apply(elem)
And if you look at the method apply
onFunction1
, you can see that the types line up.
So, we just think of the set as an indicator function, and then we bury that under three layers of syntactic sugar.
Update to answer the comment: Representing a set as an indicator function allows infinite sets (and many other sets) to be modeled much more naturally than a regular list-based view. Suppose I want, for example, a set of all odd numbers. Using the view presented here, it's easy:
val odds: Set[Int] = (_ % 2 != 0)
Try to do the same with HashSet
eg.
source to share