Last active
December 11, 2018 12:45
-
-
Save frgomes/ae2d1ec7b08d9d7a2774fbd49737d961 to your computer and use it in GitHub Desktop.
scala - Count elements per category
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)
)