2014-07-24

juan_gandhi: (VP)
2014-07-24 10:00 pm
Entry tags:

new version of grouping function

  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.