Skip to content

Instantly share code, notes, and snippets.

@fthomas
Last active December 15, 2015 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fthomas/5294915 to your computer and use it in GitHub Desktop.
Save fthomas/5294915 to your computer and use it in GitHub Desktop.
import scala.language.higherKinds
import scala.collection.TraversableLike
def minGroupBy[CC[A], A, B](c: CC[A])(f: A => B)
(implicit ev1: CC[A] => TraversableLike[A, CC[A]],
ev2: Ordering[B]): CC[A] = {
val grouped = c.groupBy(f)
if (grouped.nonEmpty) grouped.minBy(_._1)._2 else c
} //> minGroupBy: [CC[A], A, B](c: CC[A])(f: A => B)(implicit ev1: CC[A] => scala.
//| collection.TraversableLike[A,CC[A]], implicit ev2: Ordering[B])CC[A]
minGroupBy(Set("a", "b", "ab"))(_.length) //> res0: scala.collection.immutable.Set[String] = Set(a, b)
minGroupBy(List("a", "b", "ab"))(_.length) //> res1: List[String] = List(a, b)
minGroupBy(List.empty[String])(_.length) //> res2: List[String] = List()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment