"class"
"3.14" "(" expressionterm ::= factor * term
term ::= factor
term ::= factor * term ::= factor * factor * term ::= factor * factor * factor

A | B(A)* or {A}(A)+(A)? or [A]list = "[" ( item ( "," item )* )? "]"
(\d+(\.\d*)?|\d*\.\d+)
\d is a decimal digit, \. is a period,
and + * ? | are as in EBNF~|rep(...)opt(...)class SimpleLanguageParser extends JavaTokenParsers {
def expr: Parser[Any] = term ~ opt(("+" | "-") ~ expr)
def term: Parser[Any] = factor ~ opt(("*" | "/" ) ~ term)
def factor: Parser[Any] = wholeNumber | "(" ~ expr ~ ")"
}
Parser[Any] with something more useful
lateropt(P) returns Option: Some of the
result of P, or Nonerep(P) returns List of the results of
PP ~ Q returns instance of class ~ (similar to a
pair)val parser = new SimpleLanguageParser val result = parser.parse(parser.expr, "3 - 4 * 5")
sets result to
((3~None)~Some((-~((4~Some((*~(5~None))))~None))))
(x~None) to x,
Some(y) to y, and ~ to spaces:
(3 (- (4 (* 5))))

package lab10
import scala.util.parsing.combinator._
class SimpleLanguageParser extends JavaTokenParsers {
def expr: Parser[Any] = term ~ opt(("+" | "-") ~ expr)
def term: Parser[Any] = factor ~ opt(("*" | "/" ) ~ term)
def factor: Parser[Any] = wholeNumber | "(" ~ expr ~ ")"
}
object Main {
def main(args: Array[String]) = {
val parser = new SimpleLanguageParser
val result = parser.parse(parser.expr, "3 - 4 * 5")
println(result)
}
}
Run the application. What is the output?
factor rule recurses back to the expr rule.
Give an example input to the parser that demonstrates this feature. What is
your input? What is the output?SimpleLanguageParser:
def eval(x : Any) : Int = x match {
case a ~ Some("+" ~ b) => eval(a) + eval(b)
case a ~ Some("-" ~ b) => eval(a) - eval(b)
case a ~ Some("*" ~ b) => eval(a) * eval(b)
case a ~ Some("/" ~ b) => eval(a) / eval(b)
case a ~ None => eval(a)
case a : String => Integer.parseInt(a)
case "(" ~ a ~ ")" => eval(a)
}
In your main program, print the value computed by
parser.eval(result.get). What output do you get when the
parser input is 3 - 4 * 5? 3 * 4 - 5?
eval function do? val x = 3 + 4 * y
Add a valdef type to the combinator parser that represents
such a definition, and enable identifiers in factor. (Hint:
Scaladoc of JavaTokenParsers)
val x = 3 + 4 * y? What do you
do to fix the problem?