Skip to content

Instantly share code, notes, and snippets.

@tpolecat
Last active December 17, 2015 00:29
Show Gist options
  • Save tpolecat/5521357 to your computer and use it in GitHub Desktop.
Save tpolecat/5521357 to your computer and use it in GitHub Desktop.
scala> val hist = List(3,2,2).groupBy(identity).mapValues(_.length)
hist: scala.collection.immutable.Map[Int,Int] = Map(2 -> 2, 3 -> 1)
scala> ((hist, List[Int]()) /: List(4, 3, 2, 2, 2, 1)) {
| case ((h, as), a) => h.get(a).map {
| case 0 => (h, a :: as)
| case n => (h + (a -> (n - 1)), as)
| }.getOrElse((h, a :: as)) }
res25: (scala.collection.immutable.Map[Int,Int], List[Int]) = (Map(2 -> 0, 3 -> 0),List(1, 2, 4))
scala>
scala> ((hist.withDefaultValue(0), List[Int]()) /: List(4, 3, 2, 2, 2, 1)) {
| case ((h, as), a) => h(a) match {
| case 0 => (h, a :: as)
| case n => (h + (a -> (n - 1)), as)
| }}
res26: (scala.collection.immutable.Map[Int,Int], List[Int]) = (Map(2 -> 0, 3 -> 0),List(1, 2, 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment