2016-07-30 62 views
4

Type classes and generic derivation看着特拉維斯布朗的優秀的博客文章中,我看到了下面的方法:類型參數中`::`的含義?

implicit def hconsParser[H: Parser, T <: HList: Parser]: Parser[H :: T] =   
    new Parser[H :: T] { 
    def apply(s: String): Option[H :: T] = s.split(",").toList match { 
     case cell +: rest => for { 
     head <- implicitly[Parser[H]].apply(cell) 
     tail <- implicitly[Parser[T]].apply(rest.mkString(",")) 
     } yield head :: tail 
    } 
    } 

什麼的H :: TParser[H :: T]意思?

此外,case cell +: rest如何處理s,即輸入到apply爲空的情況?

回答

9

H :: T是類型::[H, T],這是一個與HList類型H和尾部與T <: HList類型頭部的綴形式。即我們正在尋找類型爲::[H, T]Parser

中綴用法是這樣實現的,其中infix可以是任何名稱:

scala> trait infix[A, B] 

scala> def test[A, B](ab: A infix B) = ??? 
test: [A, B](ab: infix[A,B])Nothing 

而且,這如何case cell +: rest處理的情況下s,即輸入apply是空的?

如果s是一個空字符串,則s.split(",").toList將簡單地是一個List與空字符串作爲其單個元件。然後case cell +: rest將永遠不會運行到一個空的列表中。