corvus_192 corvus_192 - 1 month ago 17
Scala Question

how to remove sub list

How can I remove all occurrences of a sublist from a list, eg

List(1, 2, 3, 4, 5, 6, 7, 4, 8, 9, 10, 5).removeSubList(4, 5)


should remove all occurrences of (4, 5) (in this order!), so it returns

List(1, 2, 3, 6, 7, 4, 8, 9, 10, 5)

Answer

A recursive solution using indexOfSlice:

def removeSubList(l: List[Int], sublist: List[Int]): List[Int] = l.indexOfSlice(sublist) match {
  case -1 => l
  case index => removeSubList(l.patch(index, Nil, sublist.length), sublist)
}

// all of these print List(1 ,2 ,3):
println(removeSubList(List(1,2,3), List(4,5)))
println(removeSubList(List(1,2,3,4,5), List(4,5)))
println(removeSubList(List(4,5,1,2,3), List(4,5)))
println(removeSubList(List(4,5,1,2,4,5,3), List(4,5)))

EDITED:

  • (thanks @corvus_192) reverting to using indexOfSlice version instead of using diff, which ignores sublist order.
  • (thanks @The Archetypal Paul) using patch for cleaner removal of sublist