Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created February 4, 2016 21:04
Show Gist options
  • Save fancellu/716963eb48a8a3ff905f to your computer and use it in GitHub Desktop.
Save fancellu/716963eb48a8a3ff905f to your computer and use it in GitHub Desktop.
Example of grouping list items based on custom predicate
val li=List(2, 3, 4, 5, 6, 10, 11,20, 21, 22) //> li : List[Int] = List(2, 3, 4, 5, 6, 10, 11, 20, 21, 22)
def groupList[T](list: List[T],inGroup: (T,T)=>Boolean) = {
def group(lst: List[T], acc: List[T]): List[List[T]] = (lst,acc) match {
case (Nil,_) => acc.reverse :: Nil
case (h :: t,Nil) => group(t, h :: acc)
case (h :: t,ah :: _) if inGroup(h,ah) => group(t, h :: acc)
case (h :: t,_) => acc.reverse :: group(t, h :: Nil)
}
group(list, List.empty)
} //> groupList: [T](list: List[T], inGroup: (T, T) => Boolean)List[List[T]]
def oneApart(x:Int,y:Int)=x-y==1 //> oneApart: (x: Int, y: Int)Boolean
groupList(li,oneApart) //> res0: List[List[Int]] = List(List(2, 3, 4, 5, 6), List(10, 11), List(20, 21,
//| 22))
def fourOrLessApart(x:Int,y:Int)=x-y <=4 //> fourApart: (x: Int, y: Int)Boolean
groupList(li,fourOrLessApart) //> res1: List[List[Int]] = List(List(2, 3, 4, 5, 6, 10, 11), List(20, 21, 22))
//|
val li2="Hello wooorld".toList //> li2 : List[Char] = List(H, e, l, l, o, , w, o, o, o, r, l, d)
def same(x:Char,y:Char)=x==y //> same: (x: Char, y: Char)Boolean
groupList(li2,same) //> res2: List[List[Char]] = List(List(H), List(e), List(l, l), List(o), List( )
//| , List(w), List(o, o, o), List(r), List(l), List(d))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment