Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 920
zaxme Avatar asked Sep 13 '25 21:09

zaxme


1 Answers

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.

like image 110
Marth Avatar answered Sep 15 '25 17:09

Marth