Skip to content

Instantly share code, notes, and snippets.

@jrudolph
Created January 22, 2009 15:30
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 jrudolph/50572 to your computer and use it in GitHub Desktop.
Save jrudolph/50572 to your computer and use it in GitHub Desktop.
import scala.collection.immutable.{TreeMap,SortedMap}
def fromListWith[A,K<%Ordered[K]](seq:Iterable[(K,A)])(f: (A,A)=>A):SortedMap[K,A] =
seq.foldLeft(TreeMap.empty[K,A]){
(map:TreeMap[K,A],entry) =>
val (key,ele) = entry
// update entry by either applying f to existing elements or
// just starting a new entry
map.update(key,map.get(key).map(f(ele,_)).getOrElse(ele))
}
def &&&[A,B,C](f1:A=>B,f2:A=>C) = (a:A) => (f1(a),f2(a))
def clusterBy[A,B<%Ordered[B]](it:Iterable[A])(f:A=>B) =
fromListWith(it.map(&&&(f,List(_))))(_++_)
def words(str:String) = str.split(' ')
def main(args:Array[String]){
val ws = words("das ist das haus des nikolaus")
clusterBy(ws)(_.length)
clusterBy(ws)(_.first)
clusterBy(ws)(_.last)
()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment