Reputation: 12104
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
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