Skip to content

Instantly share code, notes, and snippets.

@gigiigig
Last active August 29, 2015 14:26
Show Gist options
  • Save gigiigig/e2f2ec54fda412444656 to your computer and use it in GitHub Desktop.
Save gigiigig/e2f2ec54fda412444656 to your computer and use it in GitHub Desktop.
Custom implementation of HList and print operation.
object foo extends App {
trait HList
trait HNil extends HList
case object HNil extends HNil {
def ::[H](h: H): H :: HNil = foo.::(h, HNil)
}
case class ::[H, T <: HList](h: H, t: T) extends HList { self =>
def ::[H](h: H) = foo.::(h, self)
}
trait Print[L <: HList] {
def apply(l: L): String
}
object Print {
def apply[L <: HList](implicit p: Print[L]) = p
implicit val pnil: Print[HNil] = new Print[HNil] {
def apply(l: HNil) = "HNil"
}
implicit def pl[H, T <: HList](implicit pt: Print[T]): Print[H :: T] = new Print[H :: T] {
def apply(l: H :: T) = s"(${l.h}:${l.h.getClass.getSimpleName}) :: " + pt(l.t)
}
}
implicit class HListOps[L <: HList](l: L) {
def print(implicit p: Print[L]) = p(l)
}
/*
scala> import foo._
import foo._
scala> 1 :: 2 :: false :: HNil
res0: foo.::[Int,foo.::[Int,foo.::[Boolean,foo.HNil]]] = ::(1,::(2,::(false,HNil)))
scala> res0.print
res1: String = (1:Integer) :: (2:Integer) :: (false:Boolean) :: HNil
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment