Skip to content

Instantly share code, notes, and snippets.

@mpilquist
Created November 24, 2015 15:59
Show Gist options
  • Save mpilquist/00ffedb3953be3ea61bb to your computer and use it in GitHub Desktop.
Save mpilquist/00ffedb3953be3ea61bb to your computer and use it in GitHub Desktop.
Unwrapping an hlist
package foo
import shapeless._
import shapeless.poly._
trait Extract[F[_]] {
def extract[A](fa: F[A]): A
def extractAll[K <: HList](k: K)(implicit m: ops.hlist.Mapper[Extract.extract.type, K]) =
Extract.extractAll[F, K](k)(this, m)
}
object Extract {
def apply[F[_]](implicit F: Extract[F]): Extract[F] = F
def extractAll[F[_], K <: HList](k: K)(implicit F: Extract[F], m: ops.hlist.Mapper[extract.type, K]) = {
k map extract
}
object extract extends Poly1 {
implicit def default[F[_] : Extract, A] = at[F[A]] { fa => Extract[F].extract(fa) }
}
}
case class Wrap[A](value: A)
object Wrap {
implicit val extract: Extract[Wrap] = new Extract[Wrap] {
def extract[A](w: Wrap[A]) = w.value
}
}
object Usage extends App {
val wrapped = Wrap(1) :: Wrap(true) :: HNil
val unwrapped = Extract[Wrap].extractAll(wrapped)
println(unwrapped)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment