Skip to content

Instantly share code, notes, and snippets.

@maasg
Created June 8, 2014 14:24
Show Gist options
  • Select an option

  • Save maasg/89be8b089cdb012ffbd8 to your computer and use it in GitHub Desktop.

Select an option

Save maasg/89be8b089cdb012ffbd8 to your computer and use it in GitHub Desktop.
Cluster sequential elements given a predicate
// 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