zaxme
zaxme

Reputation: 1095

Scala partition a set

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

Upvotes: 4

Views: 604

Answers (1)

Marth
Marth

Reputation: 24812

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.

Upvotes: 7

Related Questions