0

Say I have a integer list:

val list = List(1,2,3,4,5,3,6,7)

I want to split the list by the integer 3, so I can get a list of list:

list.splitBy(3)
// returns List(List(1,2), List(4,5), List(6,7))

Is there any built-in or neat way to do this?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • 1
    I'm sure this can be done with a `fold` with two accumulators, one for the List of Lists (the result of the fold) and one for the sub lists which will be appended to until it hits a 3 where it will then add that sub list to the List of Lists and clear out the sub list for the next set of numbers. – cmbaxter Apr 04 '15 at 13:04

1 Answers1

1

This is a little rough, but something like this could work:

val list = List(1,2,3,4,5,3,6,7)

println(splitListAt(list, 3))

def splitListAt(list:List[Int], toSplit:Int) = {
  val (master, lastSub) = list.foldLeft((List.empty[List[Int]], List.empty[Int])){
    case ((master, sub), i) if i == toSplit => (master :+ sub, List.empty[Int])
    case ((master, sub), i) => (master, sub :+ i)
  }
  master :+ lastSub
}
cmbaxter
  • 35,283
  • 4
  • 86
  • 95