Created
January 22, 2009 15:30
-
-
Save jrudolph/50572 to your computer and use it in GitHub Desktop.
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.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