Jul. 25th, 2014
list grouping, take 3
Jul. 25th, 2014 11:20 amNow two versions:
1. With tail recursion, via
lomeo
2. With fold (corrected thrice)
More critique?
1. With tail recursion, via
def groupByRelationship[T](xs: List[T])(p: (T,T) => Boolean) = {
def go(xs: List[T], accum: List[List[T]]): List[List[T]] = (xs, accum) match {
case (Nil, _) => accum.reverse map (_.reverse)
case (x::xs, Nil) => go(xs, List(List(x)))
case (x::xs, ((ys@(y::_))::rest)) => go(xs, if (p(y, x)) (x::ys)::rest else
List(x)::ys::rest)
}
go(xs, Nil)
}
2. With fold (corrected thrice)
def groupByRelationship[T](p: (T,T) => Boolean)(xs: List[T]) = {
val (seg,acc) = ((List[T](),List[List[T]]()) /: xs) {
case ((y::ys, a), x) if p(y,x) => (x ::y ::ys, a)
case ( (ys, a), x) => (x::Nil, ys.reverse::a)
}
(seg.reverse::acc).reverse drop 1
}
More critique?