Huy Vo Huy Vo - 2 months ago 32
Scala Question

Scala's parser combinator: parse an option

Say I have a parser like this:

trait PT {}

trait StatementPT extends PT{}

...

class LoopConditionPT(val operation: String, val variable: IdentPT, val condition: Option[(String,ExpressionPT)]) extends StatementPT { ... }


The
Option[(String,ExpressionPT)])
bug me for a day, I mean I can deal with
Option[T]
, but
Option[(T,T)]
? I wrote this
def loopCondition
but it always raises error:

def loopCondition: Parser[LoopConditionPT] = "some string" ~ var ~ opt(("TIL"|"WILE") ~ expression) ^^ {
case a ~ b ~ Some(c ~ d) => new LoopCondition(a, b, Option[(c, d)])
case a ~ b ~ None => new LoopCondition(a, b, Option[("None", -1)])


Can someone help me fixes the
loopCondition
? Thanks.

mAt mAt
Answer

[] are used for denoting types. When you want to create an Option - i.e. call Option.apply() - use parenthesis instead of square brackets. So instead of

new LoopCondition(a, b, Option[(c, d)])

say

new LoopCondition(a, b, Option((c, d)))

or you can use syntactic sugar for tuples and say

new LoopCondition(a, b, Option(c -> d))