Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active December 11, 2018 12:45
Show Gist options
  • Save frgomes/ae2d1ec7b08d9d7a2774fbd49737d961 to your computer and use it in GitHub Desktop.
Save frgomes/ae2d1ec7b08d9d7a2774fbd49737d961 to your computer and use it in GitHub Desktop.
scala - Count elements per category
/** Group objects in categories. Requires ordered input. */
def groups[A, K](s: Iterable[A], acc: Stream[Iterable[A]] = Stream.empty[Iterable[A]])
(implicit groupKeyOf: (A => K)): Iterable[Iterable[A]] = {
s match {
case first :: _ =>
val (left, right) = s.span(p => groupKeyOf(p) == groupKeyOf(first))
groups(right, acc :+ left)(groupKeyOf)
case Nil => acc
}
}
@frgomes
Copy link
Author

frgomes commented Dec 11, 2018

Example of usage

val ints = Seq( 1, 2, 3, 2, 3, 4, 5, 6, 8, 9, 5, 3, 4, 5, 6, 3, 6, 7, 3)
implicit def intIdentity(i: Int): Int = i
groups(ints.sorted)

Output

ints: Seq[Int] = List(1, 2, 3, 2, 3, 4, 5, 6, 8, 9, 5, 3, 4, 5, 6, 3, 6, 7, 3)
defined function intIdentity
res13_2: Seq[Seq[Int]] = List(
List(1),
List(2, 2),
List(3, 3, 3, 3, 3),
List(4, 4),
List(5, 5, 5),
List(6, 6, 6),
List(7),
List(8),
List(9)
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment