【发布时间】:2010-12-06 06:34:22
【问题描述】:
我正在用 Scala 编写一个小型方案解释器,但在方案中解析列表时遇到了问题。我的代码解析包含多个数字、标识符和布尔值的列表,但如果我尝试解析包含多个字符串或列表的列表,它就会窒息。我错过了什么?
这是我的解析器:
class SchemeParsers extends RegexParsers {
// Scheme boolean #t and #f translate to Scala's true and false
def bool : Parser[Boolean] =
("#t" | "#f") ^^ {case "#t" => true; case "#f" => false}
// A Scheme identifier allows alphanumeric chars, some symbols, and
// can't start with a digit
def id : Parser[String] =
"""[a-zA-Z=*+/<>!\?][a-zA-Z0-9=*+/<>!\?]*""".r ^^ {case s => s}
// This interpreter only accepts numbers as integers
def num : Parser[Int] = """-?\d+""".r ^^ {case s => s toInt}
// A string can have any character except ", and is wrapped in "
def str : Parser[String] = '"' ~> """[^""]*""".r <~ '"' ^^ {case s => s}
// A Scheme list is a series of expressions wrapped in ()
def list : Parser[List[Any]] =
'(' ~> rep(expr) <~ ')' ^^ {s: List[Any] => s}
// A Scheme expression contains any of the other constructions
def expr : Parser[Any] = id | str | num | bool | list ^^ {case s => s}
}
【问题讨论】:
-
你如何处理空白?
-
为什么需要
^^ {case s => s}? -
@MJP +1 ,
^^ {case s => s}可以删除 -
@Gabe One 会假定
RegexParsers对空白的默认处理是有效的。 -
失败的测试用例会很有用。