Jul. 24th, 2014

juan_gandhi: (VP)
  def groupByRelationship[T](p: ((T,T) => Boolean)) = {
    new (List[T] => List[List[T]]) { group =>

      def apply(xs: List[T]): List[List[T]] =
        xs match {
          case Nil => Nil
          case x::Nil => (x::Nil)::Nil
          case x::y::tail if x == y || p(x,y) =>
            val (h::t) = group(y::tail)
            (x::h)::t
          case x::ys => (x::Nil)::group(ys)
        }
    }
  }


or, alternatively,
  def groupByRelationship[T](p: ((T,T) => Boolean)) = {
    new (List[T] => List[List[T]]) { group =>

      def apply(xs: List[T]): List[List[T]] =
        xs match {
          case Nil    => Nil
          case x::Nil => (x::Nil)::Nil
          case x::ys  =>
            val tail = group(ys)
            if (x == ys.head || p(x, ys.head)) (x::tail.head)::tail.tail
            else                               (x::Nil)::tail
        }
    }
  }



Like in Haskell.
Thanks [livejournal.com profile] lomeo, [livejournal.com profile] huzhepidarasa, [livejournal.com profile] cousin_it, [livejournal.com profile] sassa_nf for their critique.

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 09:34 am
Powered by Dreamwidth Studios