如何按条件将列表拆分为两个列表

How to split a List by a condition into two lists

我正在尝试以函数式方式编写此函数的正文:

grouping[T](xs: List[T], rule: T => Boolean): Tuple2[List[T], List[T]]

为了像这样使用它:

println(grouping(List(1, 2, 100, 3, 4, 501, 12), (x: Int) => x >= 100))
println(grouping(List('A', 'C', 'Z', 'T', 'O', 'P', 'N', 'M', 'Y'), (x: 
Char) => x >= 'J'))

并得到:

(List(100, 501), List(1, 2, 3, 4, 12))
(List(Z, T, O, P, N, M, Y),List(A, C))

List 提供了 partition 方法,它就是这样做的:

List(1, 2, 100, 3, 4, 501, 12).partition(_ >= 100)

和returns:

(List(100, 501), List(1, 2, 3, 4, 12))

来自documentation

def partition(p: (T) => Boolean): (List[T], List[T])

Partitions this traversable collection in two traversable collections according to a predicate. partition(p: (T) => Boolean): (List[T], List[T]) Partitions this traversable collection in two traversable collections according to a predicate.


我们可以将它封装在一个函数中,该函数在输入中接受一个谓词:

def grouping[T](xs: List[T], rule: T => Boolean): (List[T], List[T]) = {
  xs.partition(rule)
}

以这种方式应用它:

grouping(List(1, 2, 100, 3, 4, 501, 12), (i: Int) => i >= 100)
grouping(List('A', 'C', 'Z', 'T', 'O', 'P', 'N', 'M', 'Y'), (x: Char) => x >= 'J')