Electric Coffee
Electric Coffee

Reputation: 12104

Matching a sublist in the middle of a list

I'm writing a simple parser that uses Scala's pattern matching capabilities.

However it seems to be quite cumbersome to parse something coming after a variable number of tokens.

Is there a way for me to do something like the following:

def parse(toks: List[Token]) = toks match {
  case FuncDef :: Id(v) :: LeftParen :: { args } :: RightParen :: Nil => 
    // impl goes here
}

where { args } is a sublist.

So say if the Token list looks like this:

List(FuncDef, Id("foo"), LeftParen, Id("x"), Id("y"), Id("z"), RightParen)

{ args } would then match Id("x"), Id("y"), Id("z")

Is this feasible, or do I need to go and do this

def parse(toks: List[Token]) = toks match {
  case FuncDef :: Id(v) :: LeftParen :: tail => 
    // impl goes here
}

and then go and manually check if RightParen appears in the correct place in tail?

Upvotes: 3

Views: 427

Answers (1)

Kolmar
Kolmar

Reputation: 14224

You can use the :+ matcher to split off the last element of any Seq. So the full matching expression would look like this:

case FuncDef +: Id(v) +: LeftParen +: args :+ RightParen =>

For lists +: is basically an equivalent to ::, so I used it here for symmetry with :+.

Upvotes: 5

Related Questions