Skip to content

Instantly share code, notes, and snippets.

@gigiigig
Last active August 29, 2015 14:26
Show Gist options
  • Save gigiigig/ee931448b6ce662b9032 to your computer and use it in GitHub Desktop.
Save gigiigig/ee931448b6ce662b9032 to your computer and use it in GitHub Desktop.
Implement HList reverse
import shapeless._
object console extends App {
trait Reverse[T <: HList] {
type Out <: HList
def reverse(t: T): Out
}
object Reverse {
implicit def r[L <: HList, A <: HNil, Out0 <: HNil](implicit rtr: ReverseTR[L, A, Out0]): Reverse[L] = new Reverse[L] {
type Out = Out0
def reverse(l: L): Out = rtr.reverse(l, HNil.asInstanceOf[A])
}
trait ReverseTR[L <: HList, A <: HList, Out <: HList] {
def reverse(l: L, a: A): Out
}
object ReverseTR {
implicit def rtrnil[A <: HList]: ReverseTR[HNil, A, A] = new ReverseTR[HNil, A, A] {
def reverse(l: HNil, a: A): A = a
}
implicit def rtrcons[H, T <: HList, A <: HList, Out <: HList]
(implicit rtr: Lazy[ReverseTR[T, H :: A, Out]]): ReverseTR[H :: T, A, Out] =
new ReverseTR[H :: T, A, Out] {
def reverse(l: H :: T, a: A): Out = rtr.value.reverse(l.tail, l.head :: a)
}
}
}
implicit class PrintOps[T <: HList](t: T) {
def reverse(implicit r: Reverse[T]): r.Out = r.reverse(t)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment