Reputation: 43
Consider the LL1 grammer: ::= | | num ::= + ::= *
Now consider the set of scala cases classes. Below code is given and I only need to add code inside the expr() and times() method
sealed abstract class Token
case object PlusToken extends Token
case object TimesToken extends Token
case class NumToken(value:Int) extends Token
def isExpr(tokens:List[Token]):Boolean = {
var remaining = tokens
object ParseError extends Exception
def expr():Unit = // ** add code here
def plus():Unit = {
if (remaining.headOption != Some(PlusToken)) throw ParseError
remaining = remaining.tail
expr()
expr()
}
def times():Unit = // ** add code here
try {
expr()
if (remaining.isEmpty)
true
else
false
} catch {
case ParseError => false
}
}
I need to add code for the expr() and times() method in such a way that isExpr() returns whether the list of tokens passed to it can be derived from according to the grammar.
Output should be in following ways:
isExpr(List(PlusToken, NumToken(5), NumToken(3))) => true
isExpr(List(PlusToken, PlusToken)) => false
isExpr(List(PlusToken, NumToken(1))) => false
isExpr(List(PlusToken, NumToken(9), NumToken(8), NumToken(7))) => false
Following is my code for expr() and times() method:
sealed abstract class Token
case object PlusToken extends Token
case object TimesToken extends Token
case class NumToken(value:Int) extends Token
def isExpr(tokens:List[Token]):Boolean =
{
var remaining = tokens
object ParseError extends Exception
def expr():Unit = // ** add code here
{
if(remaining.HeadOption == Some(PlusToken))
plus()
else if(remaining.headOption == Some(TimesToken))
times()
else remaining = remaining.tail
}
def plus():Unit =
{
if (remaining.headOption != Some(PlusToken)) throw ParseError
remaining = remaining.tail
expr()
expr()
}
def times():Unit = // ** add code here
{
if (remaining.headOption != Some(TimesToken)) throw ParseError
remaining = remaining.tail
expr()
expr()
}
try
{
expr()
if (remaining.isEmpty)
true
else
false
} catch
{
case ParseError => false
}
def main(argv: Array[String]) {}
}
For my code, I am getting compile time error. Error is: excepted class or object definition. Also, I am not sure how to use the main class to print whatever is expected. Please look into my scala code as I am completely new to it and provide your input.
Upvotes: 0
Views: 57
Reputation: 67075
You are writing your code outside of an object (class
, trait
, or object
) as the error is stating. So you need to wrap the code inside of one of those structures.
Example for object
object Main {
def someMethod....
def main(argv: Array[String]) {
...main entry point of your system...
}
}
Upvotes: 1