Trying to restrict types in shapeless' HList

422 views
Skip to first unread message

Oliver Ruebenacker

unread,
Oct 23, 2015, 12:30:57 PM10/23/15
to scala-user

     Hello,

  I want to restrict the types of the elements of a shapeless HList. I tried:

import shapeless.{HList, LUBConstraint}

case class A[L <: HList](list: L)(implicit val c: LUBConstraint[L, String]) {
  def head: String = list.head
}

  This does not compile, giving me:

Error:(21, 27) could not find implicit value for parameter c: shapeless.ops.hlist.IsHCons[L]
  def head: String = list.head
                          ^

Error:(21, 27) not enough arguments for method head: (implicit c: shapeless.ops.hlist.IsHCons[L])c.H.
Unspecified value parameter c.
  def head: String = list.head
                          ^

  Any idea? Thanks!

     Best, Oliver

--
Oliver Ruebenacker
Senior Software Engineer, Diabetes Portal, Broad Institute

William Harvey

unread,
Oct 23, 2015, 12:35:00 PM10/23/15
to scala-user
Here you go:

case class A[L <: HList](list: String :: L)(implicit val c: LUBConstraint[L, String]) {

  def head: String = list.head
}

Oliver Ruebenacker

unread,
Oct 23, 2015, 12:40:24 PM10/23/15
to William Harvey, scala-user

     Hello,

  Thanks, but that only restricts the type of the head, right?

  OK, my example was bad, because it doesn't make sense for Strings.

  How would I restrict all elements of an HList to be of type Seq[_]? Thanks!

     Best, Oliver

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

William Harvey

unread,
Oct 23, 2015, 12:52:33 PM10/23/15
to scala-user, harv...@cse.ohio-state.edu
It restricts the type of the head and tail.

If you want Seq[_] elements in your HList, try this:

    case class A[L <: HList](list: Seq[_] :: L)(implicit val c: LUBConstraint[L, Seq[_]]) {
      def head: Seq[_] = list.head
    }
   
    A(Seq("Hello") :: HNil)
    A(Seq("Hello") :: Seq("World") :: HNil)
    A(Seq("Hello") :: Seq(42, 42f, "Blah") :: HNil)
    val blah = A(Seq("Hello") :: Seq(42, 42f, "Blah", java.awt.Color.red) :: HNil)
   
    val theHead: Seq[Any] = blah.head
   
    // Doesn't compile, as expected.
    // A(42 :: HNil)

Does that help?

Cheers,

William

Oliver Ruebenacker

unread,
Oct 23, 2015, 12:53:38 PM10/23/15
to William Harvey, scala-user
Awesome, thanks!
Reply all
Reply to author
Forward
0 new messages