petrbel
petrbel

Reputation: 2528

Scala list pattern matching in value declaration

Assuming the following list of four tuples:

> def getList = List( (1,2), (3,4), (5,6), (7,8) )

I want to parse it into three sections in new values declaration like this - the last tuple (l1,l2), the penultimate tuple (p1,p2) and the rest of the list rest.

Moreover, I'd like to pattern-match the tuples as well. Example:

> val (rest :: (p1, p2) :: (l1, l2) ) = getList
rest = List( (1,2), (3,4) )
p1 = 5
p2 = 6
l1 = 7
l2 = 8

The expected output does not work because :: expects a list as its right-side argument. I tried several different possibilities such as ::: with List wrapper. However, I haven't managed to achieve the goal.

Is it even possible? I don't want to reverse the list - instead, I'm looking for an elegant solution that is applicable to value declaration (thus no match please). I hope in one-line solution.

Edit: Scala code runner version 2.9.2

Upvotes: 1

Views: 147

Answers (1)

Odomontois
Odomontois

Reputation: 16308

You could use the :+ matcher object:

val rest :+ ((p1, p2)) :+ ((l1, l2))  = getList

It's the part of standard library since scala 2.10

For previous version you redefine it yourself using source

Upvotes: 2

Related Questions