I was looking at how to split a set in two based on the contents of a third set. Accidentally I stumbled upon this solution:
val s = Set(1,2,3)
val s2 = Set(4,5,6)
val s3 = s ++ s2
s3.partition(s)
res0: (scala.collection.immutable.Set[Int],scala.collection.immutable.Set[Int]) = (Set(1, 2, 3),Set(5, 6, 4))
The signature of partition
is as follows:
def partition(p: A => Boolean): (Repr, Repr)
Can someone explain to me how providing a set instead of a function works?
Thanks in advance
A set s: Set[A]
is a function A => Boolean
: for any value a
of A
you return whether s
contains a
or not.
scala> val f: Int => Boolean = Set(1,2,3)
f: Int => Boolean = Set(1, 2, 3)
scala> f(1)
res0: Boolean = true
scala> f(4)
res1: Boolean = false
If you look a the documentation for .apply, you'll see
def apply(elem: A): Boolean
Tests if some element is contained in this set.This method is equivalent to contains. It allows sets to be interpreted as predicates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With