juan_gandhi: (VP)
[personal profile] juan_gandhi
Now two versions:

1. With tail recursion, via [livejournal.com profile] lomeo
  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?
This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

June 2025

S M T W T F S
1 2345 6 7
8 9 10 11 121314
15161718 1920 21
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 26th, 2025 02:18 pm
Powered by Dreamwidth Studios