Jul. 25th, 2014

juan_gandhi: (VP)
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?
juan_gandhi: (VP)
wiki

A BS dating from '50-s

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

August 2025

S M T W T F S
      12
3456789
10 11 12 13141516
171819 20212223
2425 2627282930
31      

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Aug. 28th, 2025 02:41 am
Powered by Dreamwidth Studios