Created
June 25, 2010 00:21
-
-
Save huynhjl/452195 to your computer and use it in GitHub Desktop.
clusterBy
This file contains 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
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