Skip to content

Instantly share code, notes, and snippets.

@huynhjl
Created June 25, 2010 00:21
Show Gist options
  • Save huynhjl/452195 to your computer and use it in GitHub Desktop.
Save huynhjl/452195 to your computer and use it in GitHub Desktop.
clusterBy
import scala.annotation._
val l = 0 until 30 toList
def div(i:Int) = i / 2
def cluster[T,U](xs:Seq[T], f:T => U): Seq[(U, Seq[T])] = {
@tailrec
def tr_cluster(acc: Seq[(U, Seq[T])], xs:Seq[T]): Seq[(U, Seq[T])] = {
if (xs.isEmpty) {
acc
} else {
val u = f(xs.head)
xs.span(x => f(x) == u) match {
case (h, t) => tr_cluster(acc :+ (u ->h ), t)
}
}
}
tr_cluster(Nil, xs)
}
val res = cluster(l, div)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment