Library contents

Scala Iterable.partition

partition traverses a collection with a predicate and returns the matching and nonmatching groups as a pair.

A simple example

Iterable.partition

  1. Start with 1, 2, 3
  2. Do this Separate values at least 2
  3. Result Pass [2, 3], fail [1]
Every item is assigned to one side of the predicate.

Syntax

Scala syntax
val (passing, failing) = values.partition(predicate)
Run this example in Scala

Save the program as Lesson.scala. Use Scala 2.13.

scalac Lesson.scala
scala Lesson

Separate passing and failing records

A quality check divides records into those that pass its rule and those that fail. Preserve both result sets so the rejected records remain available to the person reviewing the batch.

From the programval (passing, failing) = scores.partition(_ >= 50)
First output line50,80
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
    val scores = List(49, 50, 80, 12)
    val (passing, failing) = scores.partition(_ >= 50)
    println(passing.mkString(","))
    println(failing.mkString(","))
  }
}
Output
50,80
49,12

Equality with the threshold counts as a pass in this example. List preserves the original order inside each resulting group.

Scala documentation for Iterable.partition

Advertisements

Count packs on the delivery slip

A loading desk receives four item counts in sequence. The desk separates zero-quantity records for review. How many positive entries remain in the other group?

Given6 · 2 · 6 · 0
Worked result3

Review print quantities

A print room records four job quantities, including a cancelled job. The desk separates zero-quantity records for review. How many positive entries remain in the other group?

Given3 · 0 · 8 · 3
Worked result3