MaciejF
MaciejF

Reputation: 546

Scala grouping list into list tuples with one shared element

What would be short functional way to split list

List(1, 2, 3, 4, 5) into List((1,2), (2, 3), (3, 4), (4, 5))

Upvotes: 3

Views: 109

Answers (3)

oblivion
oblivion

Reputation: 6548

I have always been a big fan of pattern matching. So you could also do:

val list = List(1, 2, 3, 4, 5, 6)

  def splitList(list: List[Int], result: List[(Int, Int)] = List()): List[(Int, Int)] = {
    list match {
      case Nil => result
      case x :: Nil => result
      case x1 :: x2 :: ls => splitList(x2 :: ls, result.:+(x1, x2))
    }
  }

  splitList(list)
  //List((1,2), (2,3), (3,4), (4,5), (5,6))

Upvotes: 1

marios
marios

Reputation: 8996

(assuming you don't care if you nested pairs are Lists and not Tuples)

Scala collections have a sliding window function:

@ val lazyWindow = List(1, 2, 3, 4, 5).sliding(2)
lazyWindow: Iterator[List[Int]] = non-empty iterator

To realize the collection:

@ lazyWindow.toList
res1: List[List[Int]] = List(List(1, 2), List(2, 3), List(3, 4), List(4, 5))

You can even do more "funcy" windows, like of length 3 but with step 2:

@ List(1, 2, 3, 4, 5).sliding(3,2).toList
res2: List[List[Int]] = List(List(1, 2, 3), List(3, 4, 5))

Upvotes: 5

akuiper
akuiper

Reputation: 214947

You can zip the list with its tail:

val list = List(1, 2, 3, 4, 5)
// list: List[Int] = List(1, 2, 3, 4, 5)

list zip list.tail
// res6: List[(Int, Int)] = List((1,2), (2,3), (3,4), (4,5))

Upvotes: 3

Related Questions