Scala: sequentially create a list of tuples from list items

I am very new to Scala, so this question can be very naive.

I have a list like List[Int] = List(0, 3, 6, 12, 14, 15, 16, 17) . I am trying to create a list like this [(0,3),(3,6),(6,12)..] and so on. So far this is what I tried:

 val l1= List(0, 3, 6, 12, 14, 15, 16, 17) var l2=scala.collection.mutable.ListBuffer[(Int,Int)]() l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>{val newval=(x._1,l1(x._2+1)); l2+=newval}) 

Two questions here:

  • If I do not use val newval , i.e. I will try to execute l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>l2+=(x._1,l1(x._2+1))) , the compiler says: <console>:10: error: type mismatch; found : Int required: (Int, Int) l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>l2+=(x._1,l1(x._2+1))) <console>:10: error: type mismatch; found : Int required: (Int, Int) l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>l2+=(x._1,l1(x._2+1))) . Why is this?
  • What is the way to do this without a mutable listbuffer?
+7
immutability list scala functional-programming
source share
2 answers
  • += is a method on ListBuffer l2 that accepts duplicate parameters. This means that when you do something like this:

     scala> var l2 = scala.collection.mutable.ListBuffer[(Int, Int)]() l2: scala.collection.mutable.ListBuffer[(Int, Int)] = ListBuffer() scala> l2 += (1, 2) <console>:9: error: type mismatch; found : Int(1) required: (Int, Int) l2 += (1, 2) 

.. The compiler thinks that you are trying to add multiple ListBuffer to the ListBuffer when you are trying to add a tuple. You need an extra set of parentheses.

  l1.zipWithIndex.slice(0,l1.length-1).foreach(x=> l2 += ((x._1,l1(x._2+1)) )) 
  1. You can use sliding , which will create a β€œsliding window” over the collection to return a list of lists of a specific group size with the default step size:

     scala> List(0, 3, 6, 12, 14, 15, 16, 17).sliding(2) .map { case List(a, b) => (a, b) }.toList res10: List[(Int, Int)] = List((0,3), (3,6), (6,12), (12,14), (14,15), (15,16), (16,17)) 
+10
source share

Besides sliding, you can slide as follows:

  val l1= List(0, 3, 6, 12, 14, 15, 16, 17) val l2 = l1.take(l1.size - 1).zip(l1.tail) 

updated

  l1.zip(l1.tail) works. 
+2
source share

All Articles