6

I'm trying to process triplets in a list. Imperatively, I could do this:

for(i = 1; i < list.length-1; i++)
{
   process( list[i-1], list[i], list[i+1] )
}

Is there a List function in Scala (or how would one write it) that can do something like this:

val data = [1,2,3,4,5,6,7,8,9,10]
val tuples = data.some_magic_func
tuples would be[(1,2,3), (2,3,4), (3,4,5), (4,5,6) ... ]

Thanks!

fbl
  • 2,840
  • 3
  • 33
  • 41

3 Answers3

23

Pablo's solution isn't entirely correct, you still need to transform the list of lists into a list of tuples:

val data = List(1,2,3,4,5,6,7,8,9,10)
val tuples = data.sliding(3).toList.collect{ case List(x,y,z) => (x,y,z) }
//--> tuples: List[(Int, Int, Int)] = List((1,2,3), (2,3,4), (3,4,5), ...
Landei
  • 54,104
  • 13
  • 100
  • 195
10

I know you got the answer you wanted, but the technically correct answer is no. There's no general method that takes a list and returns tuples of variable arity because there's no way to represent that type signature in Scala at the present.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • thank you for the clarification. For my purpose, Pablo's solution works fine for me, but it's always nice to get more insight. – fbl Nov 04 '11 at 14:27
8
val data = List(1,2,3,4,5,6,7,8,9,10)
val tuples = data.sliding(3).toList
// tuples would be List(List(1,2,3), List(2,3,4), List(3,4,5), List(4,5,6) ... )
Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232
  • that's exactly what I was looking for. Will mark as 'the answer' as soon as SO will allow it. – fbl Nov 04 '11 at 04:32
  • 4
    @Pablo Fernandez: This is not correct, the result is `tuples: List[List[Int]] = List(List(1, 2, 3), List(2, 3, 4), ...` – Landei Nov 04 '11 at 08:13
  • 1
    As Landei already remarked, this answer is NOT correct, it doesn't give a list of tuples, but a list of lists. The question is clearly about list of tuples! Landei's solution is the correct one. – t0r0X Apr 28 '13 at 12:02