Scala组合器解析器-区分数字字符串和变量字符串 [英] Scala combinator parsers - distinguish between number strings and variable strings

查看:62
本文介绍了Scala组合器解析器-区分数字字符串和变量字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行Cay Horstmann的组合器解析器练习,我想知道在match语句中区分代表数字的字符串和代表变量的字符串的最佳方法:

I'm doing Cay Horstmann's combinator parser exercises, I wonder about the best way to distinguish between strings that represent numbers and strings that represent variables in a match statement:

def factor: Parser[ExprTree] = (wholeNumber | "(" ~ expr ~ ")" | ident) ^^ {
    case a: wholeNumber  => Number(a.toInt)
    case a: String => Variable(a)
}

第二行"case a:wholeNumber"不合法.我想到了一个正则表达式,但是还没有找到一种使其与"case"一起使用的方法.

The second line there, "case a: wholeNumber" is not legal. I thought about a regexp, but haven't found a way to get it to work with "case".

推荐答案

我将它分成几部分,并将案例分析推送到|中.这是组合器和真正的LL(*)解析的优点之一:

I would split it up a bit and push the case analysis into the |. This is one of the advantages of combinators and really LL(*) parsing in general:

def factor: Parser[ExprTree] = ( wholeNumber ^^ { Number(_.toInt) }
                               | "(" ~> expr <~ ")" 
                               | ident ^^ { Variable(_) } )

如果您对下划线语法不熟悉,我深表歉意.基本上,这仅表示将第 n 个参数替换为封闭函数的值".因此{ Variable(_) }等效于{ x => Variable(x) }.

I apologize if you're not familiar with the underscore syntax. Basically it just means "substitute the nth parameter to the enclosing function value". Thus { Variable(_) } is equivalent to { x => Variable(x) }.

另一个语法魔术是~><~运算符代替了~.这些运算符意味着该术语的解析应包括两个parens的语法,但是结果应仅由expr的结果确定.因此,"(" ~> expr <~ ")""(" ~ expr ~ ")"完全相同,但是不需要额外的案例分析就可以从expr检索内部结果值.

Another bit of syntax magic here is the ~> and <~ operators in place of ~. These operators mean that the parsing of that term should include the syntax of both the parens, but the result should be solely determined by the result of expr. Thus, the "(" ~> expr <~ ")" matches exactly the same thing as "(" ~ expr ~ ")", but it doesn't require the extra case analysis to retrieve the inner result value from expr.

这篇关于Scala组合器解析器-区分数字字符串和变量字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆