Her sincerly
Her sincerly

Reputation: 383

Scala iterate over two consecutive elements of a list

How would we iterate over two consecutive elements of a list and apply the difference function For instance I have this :

val list = List(List("Eat", "Drink", "Sleep", "work"), List("Eat", "Sleep", "Dance"))

I want to iterate over these two consecutive elements and calculate the difference

I've tried this but I do not know how to iterate over each two consecutive elements

list.map((a,b) => a.diff(b))

the output should be List("Drink", "work")

Upvotes: 1

Views: 1505

Answers (3)

SwiftMango
SwiftMango

Reputation: 15304

In your case, match can work perfectly fine:

val list = List(List("Eat", "Drink", "Sleep", "work"), List("Eat", "Sleep", "Dance"))
list match { case a :: b :: Nil => a diff b}

If the list does not always have 2 items, you should also have a catch-all case in match

Upvotes: 1

Jasper-M
Jasper-M

Reputation: 15086

If I understand correctly you probably want to iterate over a sliding window.

list.sliding(2).map{
  case List(a, b) => a.diff(b)
  case List(a) => a
}.toList

Alternatively you might also want grouped(2) which partitions the list into groups instead.

Upvotes: 4

QuickSilver
QuickSilver

Reputation: 4045

def main(args: Array[String]): Unit = {
    val list = List(List("Eat", "Drink", "Sleep", "work"), List("Eat", "Sleep", "Dance"));
    val diff = list.head.diff(list(1))
    println(diff)
  }

Upvotes: 1

Related Questions