How to split a list by another list in Scala

后端 未结 3 1559
清酒与你
清酒与你 2021-01-16 06:10

I am new to Scala and I need a solution to my problem. Imagine I have these lists:

val list1 = List(1,2,3,4,5,6,7,8,9,10,11)
val list2 = List(6,5)

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-16 06:41

    If what you're doing is using the second list to be the indexes on the first list:

    def indexedSplit[A](myList: List[A], indx: List[Int], acc: List[List[A]]): List[List[A]] = indx match{
      case Nil => acc.filter(_ != Nil).reverse
      case x :: xs => 
        val (h, t) = myList.splitAt(x)
        indexedSplit(t, xs, h :: acc)
    }
    

    wherein you recursively walk the index list and split the list under operation at each of those points. Finally you filter out empty lists and reverse the order since you've accumulated in reverse order.

提交回复
热议问题