Last active
August 29, 2015 14:26
-
-
Save gigiigig/ee931448b6ce662b9032 to your computer and use it in GitHub Desktop.
Implement HList reverse
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
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