Looking at Travis Brown's excellent blog post on Type classes and generic derivation, I see the following method:
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
}
}
What's the meaning of H :: T
in Parser[H :: T]
?
Also, how does this case cell +: rest
handle the case where s
, i.e. input to apply
is empty?
H :: T
is the infix form of the type ::[H, T]
, which is an HList
with a head of type H
and tail with type T <: HList
. i.e. we're looking for a Parser
for the type ::[H, T]
.
The infix usage is achieved like this, where infix
can be any name:
scala> trait infix[A, B]
scala> def test[A, B](ab: A infix B) = ???
test: [A, B](ab: infix[A,B])Nothing
Also, how does this
case cell +: rest
handle the case wheres
, i.e. input toapply
is empty?
If s
is an empty string, then s.split(",").toList
will simply be a List
with an empty string as its single element. case cell +: rest
would then never run into an empty list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With