Formal Language Processing in Scala, Solutions to Part 3

August 23rd, 2008 | In Scala

Here are the solutions to the exercises from part 3.

1.

    def ~(b: Parser) = new Parser {
      def apply(l:List[Any]) = self(l) match {
        case Some(rest) => b(rest)
        case None => None
      }
    }

2.

  trait Parser extends (List[Any] => Option[List[Any]]) {
    self =>

    // ...

    def + = self ~ (self*)

    def phrase = new Parser {
      def apply(l:List[Any]) = self.apply(l) match {
        case x @ Some(Nil) => x
        case rest => throw new Exception("Expected end of input but found "+rest)
      }
    }
  }

  def expression = new Parser {
    def apply(l:List[Any]): Option[List[Any]] = l match {
      case (i:Int) :: more => asteriskOrPlus(more) match {
        case Some(rest) => apply(rest)
        case None => Some(more)
      }
      case _ => None
    }
  }

Leave a Reply


Close
E-mail It