Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of `::` in Type Parameter?

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?

like image 206
Kevin Meredith Avatar asked Jan 06 '23 15:01

Kevin Meredith


1 Answers

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 where s, i.e. input to apply 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.

like image 121
Michael Zajac Avatar answered Jan 12 '23 10:01

Michael Zajac