Find Type Class Instances for Shapeless HList

Say I have a Show[T] trait like the one in Scalaz: https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/Show. scala # L9

I also have a Shapeless HList that might look like "1" :: 2 :: 3L :: HNil .

Is there a way to find a Show instance for each element and apply shows so that in the end I get "1" :: "2" :: "3L" :: HNil ?

If any element is of type that did not have an implicit Show instance in scope, I would like to get a compilation error.

I think that if I create an HList Show instances, I should use zipApply to get the HList , I want, but I don’t know if there is a way to get have Scala to get the HList from the Show instances, instead of creating it manually.

+6
source share
1 answer

If your goal is to use Show instances, and you don't care about creating an HList from them, the easiest way to use the polymorphic function is:

 import scalaz._, Scalaz._, shapeless._ val xs = "1" :: 2 :: 3L :: HNil object show extends Poly1 { implicit def forShowable[A: Show] = at[A](_.shows) } val strings: String :: String :: String :: HNil = xs map show 

You can get HList instances by changing Poly1 :

 object showInstance extends Poly1 { implicit def forShowable[A: Show] = at[A](_ => Show[A]) } 

In some cases, it may be useful to define your own type class to gather evidence that you have specific instances of the type class:

 trait AllShowable[L <: HList, S <: HList] { def instances: S } implicit object hnilAllShowable extends AllShowable[HNil, HNil] { def instances = HNil } implicit def hlistAllShowable[H: Show, TL <: HList, TS <: HList]( implicit ts: AllShowable[TL, TS] ) = new AllShowable[H :: TL, Show[H] :: TS] { def instances = Show[H] :: ts.instances } 

But usually matching with a polymorphic function that requires instances will work fine.

+8
source

All Articles