list grouping, take 3
Jul. 25th, 2014 11:20 am![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
Now two versions:
1. With tail recursion, via
lomeo
2. With fold (corrected thrice)
More critique?
1. With tail recursion, via
![[livejournal.com profile]](https://www.dreamwidth.org/img/external/lj-userinfo.gif)
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?