Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you turn a Scala list into pairs?

Tags:

scala

I am trying to split Scala list like List(1,2,3,4) into pairs (1,2) (2,3) (3,4), what's a simple way to do this?

like image 766
Garrett Hall Avatar asked Jun 28 '12 16:06

Garrett Hall


People also ask

What is list pair?

A list is a combination of pairs that creates a linked list. More precisely, a list is either the empty list null, or it is a pair whose first element is a list element and whose second element is a list.

How do I assign a list in Scala?

To append value inside the list object we have two approach shown below: val variable_name = List(value1, value2, value3 , soon..) 2. To assign value for ListBuffer we use += operator to assign its value anytime because ListBuffer is mutable in nature.

How do you define a list in Scala?

Scala Lists are quite similar to arrays which means, all the elements of a list have the same type but there are two important differences. First, lists are immutable, which means elements of a list cannot be changed by assignment. Second, lists represent a linked list whereas arrays are flat.


3 Answers

val xs = List(1,2,3,4)
xs zip xs.tail
  // res1: List[(Int, Int)] = List((1,2), (2,3), (3,4))

As the docs say, zip

Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs. If one of the two collections is longer than the other, its remaining elements are ignored.

So List('a,'b,'c,'d) zipped with List('x,'y,'z) is List(('a,'x), ('b,'y), ('c,'z)) with the final 'd of the first one ignored.

From your example, the tail of List(1,2,3,4) is List(2,3,4) so you can see how these zip together in pairs.

like image 143
Luigi Plinge Avatar answered Sep 22 '22 19:09

Luigi Plinge


To produce a list of pairs (i.e. tuples) try this

List(1,2,3,4,5).sliding(2).collect{case List(a,b) => (a,b)}.toList
like image 33
Jakob Odersky Avatar answered Sep 21 '22 19:09

Jakob Odersky


List(1,2,3,4).sliding(2).map(x => (x.head, x.tail.head)).toList
res0: List[(Int, Int)] = List((1,2), (2,3), (3,4))
like image 24
Brian Avatar answered Sep 24 '22 19:09

Brian