Skip to content

Instantly share code, notes, and snippets.

@leifwickland
Created December 10, 2018 20:23
Show Gist options
  • Save leifwickland/56b807cfcabd358f3ceb353fb5b00803 to your computer and use it in GitHub Desktop.
Save leifwickland/56b807cfcabd358f3ceb353fb5b00803 to your computer and use it in GitHub Desktop.
distinctby
final class ListOps[A](val l: List[A]) extends AnyVal {
def distinctBy[K](f: A => K): List[A] = {
val seen = collection.mutable.HashSet.empty[K]
@tailrec
def loop(l: List[A], distinctAccum: List[A]): List[A] = l match {
case Nil => distinctAccum
case t :: ts =>
val k = f(t)
if (seen.contains(k)) loop(ts, distinctAccum)
else {
seen += k
loop(ts, t :: distinctAccum)
}
}
loop(l, Nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment