Jul. 24th, 2014
new version of grouping function
Jul. 24th, 2014 10:00 pmdef 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]](https://www.dreamwidth.org/img/external/lj-userinfo.gif)
![[livejournal.com profile]](https://www.dreamwidth.org/img/external/lj-userinfo.gif)
![[livejournal.com profile]](https://www.dreamwidth.org/img/external/lj-userinfo.gif)
![[livejournal.com profile]](https://www.dreamwidth.org/img/external/lj-userinfo.gif)