2014-01-08 89 views
2

閱讀DSLs in Action,我看到了Sequential Combinator驗證碼:瞭解解析器組合〜輸出

def ~ [U](p: => Parser[U]): Parser[~[T, U]] = 
(for(a <- this; b <- p) yield new ~(a,b)).named("~") 

什麼是返回類型的含義:Parser[~[T, U]]

返回類型是否爲Parser,其中包含將~應用於類型爲TU的參數的結果的類型?

回答

4

~類型基本上是一個元組類型,允許中綴表示法。因此,問題中返回的解析器解析了一個與(T,U)同構的類型。中綴表示法允許編寫如下:

def intParser: Parser[Int] = ??? 
def intPair: Parser[~[Int,Int]] = intParser ~ intParser 
def product: Parser[Int] = intPair ^^ {case f1 ~ f2 => f1 * f2} 

或者在一個行,因爲它通常做:

def product: Parser[Int] = intParser ~ intParser ^^ {case f1 ~ f2 => f1 * f2} 

或許有點更加理智,有一個*分離的數字:

def product: Parser[Int] = intParser ~ ("*" ~> intParser) ^^ {case f1 ~ f2 => f1 * f2} 

請注意,~>下降了左側。