Scala 划分一个集合
Scala partition a set
我正在研究如何根据第三组的内容将一组分成两部分。我偶然发现了这个解决方案:
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))
partition
的签名如下:
def partition(p: A => Boolean): (Repr, Repr)
有人可以向我解释提供集合而不是函数的工作原理吗?
提前致谢
一个集合s: Set[A]
是一个函数A => Boolean
:对于A
的任意值a
你return s
是否包含a
。
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
如果你看 documentation for .apply,你会看到
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.
我正在研究如何根据第三组的内容将一组分成两部分。我偶然发现了这个解决方案:
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))
partition
的签名如下:
def partition(p: A => Boolean): (Repr, Repr)
有人可以向我解释提供集合而不是函数的工作原理吗?
提前致谢
一个集合s: Set[A]
是一个函数A => Boolean
:对于A
的任意值a
你return s
是否包含a
。
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
如果你看 documentation for .apply,你会看到
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.