val input = """biweekly { federal tax 20.0 percent, state tax 3.0 percent, insurance premiums 250.0 dollars, retirement savings 15.0 percent }""" val parser = new PayrollParser // <4> val biweeklyDeductions = parser.parseAll(parser.biweekly, input).get
class PayrollParser extends JavaTokenParsers { // <1> /** @return Parser[(Deductions)] */ def biweekly = "biweekly" ~> "{" ~> deductions <~ "}" ^^ { ds => // <2> Deductions("Biweekly", 26.0, ds) } }
<2>这里找到三个结束标记,biweekly,{,},以及对对{...}中内容计算deduction结果。类似箭头的操作符(其实是方法名)~>和<~表示将~一侧的标记丢掉。于是语法标记都丢掉了,只留下deductions。
^^将左边(标记)和右边(语法规则)分开。语法规则带一个参数,是保留下来的标记。如果存在多个标记,则需要一个形如{case t1 ~ t2 ~ t2 => ...}的偏函数字面量。在这个例子中,ds是Deduction实例的Vector,用于构造Deductions的实例。