Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a scala list operation that makes tuples from lists?

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!

like image 683
fbl Avatar asked Nov 04 '11 04:11

fbl


People also ask

What is the difference between tuple and list in Scala?

One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.

Does Scala list preserve order?

Lists preserve order, can contain duplicates, and are immutable.

Is list in Scala ordered?

In Scala we do not sort Lists in-place. They are immutable.


2 Answers

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), ...
like image 93
Landei Avatar answered Nov 11 '22 08:11

Landei


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.

like image 41
Daniel C. Sobral Avatar answered Nov 11 '22 07:11

Daniel C. Sobral