Created
June 8, 2014 14:24
-
-
Save maasg/89be8b089cdb012ffbd8 to your computer and use it in GitHub Desktop.
Cluster sequential elements given a predicate
This file contains hidden or 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
| // given a list of elements and a predicate over those elements, | |
| // cluster the elements into a lists of lists of elements that fulfil the predicate, preserving the order of the original list. | |
| def cluster[T](l:List[T], cond:List[T] => Boolean):List[List[T]] = { | |
| def splitCond[T](l:List[T], cond:List[T]=>Boolean):(List[T], List[T]) = { | |
| def splitCond0(l:List[T], cond:List[T]=>Boolean, cumm:List[T]):(List[T], List[T]) = l match { | |
| case Nil => (cumm, Nil) | |
| case h::t => if (cond(h::cumm)) splitCond0(t, cond, h::cumm) else (cumm,l) | |
| } | |
| splitCond0(l,cond,Nil) | |
| } | |
| l match { | |
| case Nil => Nil | |
| case list => val (grouped, rest) = splitCond(list, cond) | |
| grouped :: cluster(rest, cond) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment