更新时间:2023-11-06 19:12:10
我将它分成几部分,并将案例分析推送到|
中.这是组合器和真正的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
.