Last active
January 24, 2016 23:37
-
-
Save taig/3ff5dc94d9beae0952e9 to your computer and use it in GitHub Desktop.
Printer for (nested) Shapeless-HLists with proper brackets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Printer[L <: HList] extends DepFn1[L] with Serializable { type Out = String } | |
object Printer extends Printer0 { | |
def apply[L <: HList]( implicit printer: Printer[L] ): Printer[L] = printer | |
implicit def hnilPrinter[C]: Printer[HNil] = new Printer[HNil] { | |
override def apply( t: HNil ) = "HNil" | |
} | |
implicit def nestedHlistPrinter[H <: HList, T <: HList]( | |
implicit | |
ph: Printer[H], | |
pt: Printer[T] | |
): Printer[H :: T] = new Printer[H :: T] { | |
override def apply( t: H :: T ): Out = s"(${ph( t.head )}) :: ${pt( t.tail )}" | |
} | |
} | |
trait Printer0 { | |
implicit def hconsPrinter[H, T <: HList]( | |
implicit | |
p: Printer[T] | |
): Printer[H :: T] = new Printer[H :: T] { | |
override def apply( t: H :: T ): Out = s"${t.head} :: ${p( t.tail )}" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
scala> import shapeless._ | |
import shapeless._ | |
scala> def print[H <: HList]( h: H )( implicit p: Printer[H] ) = p( h ) | |
print: [H <: shapeless.HList](h: H)(implicit p: Printer[H])p.Out | |
scala> 1 :: 2 :: ( "foo" :: 3 :: ( "bar" :: HNil ) :: HNil ) :: HNil | |
res0: shapeless.::[Int,shapeless.::[Int,shapeless.::[shapeless.::[String,shapeless.::[Int,shapeless.::[shapeless.::[String,shapeless.HNil],shapeless.HNil]]],shapeless.HNil]]] = 1 :: 2 :: foo :: 3 :: bar :: HNil :: HNil :: HNil | |
scala> print( res0 ) | |
res1: String = 1 :: 2 :: (foo :: 3 :: (bar :: HNil) :: HNil) :: HNil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment