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的實例。