Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An elegant way of creating a Scala sequence that comprises lagged tuples

Tags:

tuples

scala

seq

I want to create a Scala sequence comprising tuples. The input is a text file like this:

A
B
C
D
E

I'm looking for an elegant way to construct "lagged" tuples like this:

(A, B), (B, C), (C, D), (D, E)
like image 947
Dronkel Avatar asked Dec 03 '22 00:12

Dronkel


2 Answers

The easiest way to do this is by using the tail and zip:

val xs = Seq('A', 'B', 'C', 'D', 'E')
xs zip xs.tail

If efficiency is a concern (i.e. you don't want to create an extra intermediate sequence by calling tail and the Seq you use are not Lists, meaning that tail takes O(n)) then you can use views:

xs zip xs.view.tail
like image 107
axel22 Avatar answered Dec 22 '22 06:12

axel22


I'm not quite sure how elegant it is, but this will work for at least all lists of more than 1 element:

val l = List('A,'B,'C,'D,'E,'F)
val tupled = l.sliding(2).map{case x :: y :: Nil => (x,y)}

tupled.toList
// res8: List[(Symbol, Symbol)] = List(('A,'B), ('B,'C), ('C,'D), ('D,'E), ('E,'F))

If you want something more elegant than that, I'd advise you look at Shapeless for nice ways to convert between lists and tuples.

like image 22
Impredicative Avatar answered Dec 22 '22 06:12

Impredicative