來看個簡單的例子
List(1, 2, 3, 1, 2).partition(_ == 2)
換產生
res0: (List[Int], List[Int]) = (List(2, 2),List(1, 3, 1))
第一個 tuple 的元素是滿足條件的 list,第二個 tuple 的元素是不滿足條件的 list。
有了 partition ,就可以很容易作到一些事情,如建立字元出現頻率的對照表
def makeMap(data: List[Char], output: Map[Char, Int]): Map[Char, Int] = data match {
case x :: xs => {
val (expected, rest) = data.partition(_ == x)
makeMap(rest, output + (x -> expected.length))
}
case Nil => output
}
沒有留言:
張貼留言