Search code examples
scalatuplesseq

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


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)

Solution

  • 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