Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- scala> :paste
- // Entering paste mode (ctrl-D to finish)
- import shapeless.ops.traversable.FromTraversable
- import shapeless.syntax.std.traversable._
- import shapeless._
- class TypeGenerator[T, N <: Nat] { type Result <: HList }
- trait LowPriorityTypeGenerator {
- implicit def hList[T, N <: Nat, L <: HList](implicit t: TypeGenerator[T, N]{ type Result = L }): TypeGenerator[T, Succ[N]]{ type Result = T :: L } =
- new TypeGenerator[T, Succ[N]]{ type Result = T :: L }
- }
- object TypeGenerator extends LowPriorityTypeGenerator {
- implicit def hnil[T]: TypeGenerator[T, _0]{ type Result = HNil } = new TypeGenerator[T, _0]{ type Result = HNil }
- }
- def toHList[T, TResult <: HList](l: List[T], n: Nat)(implicit tg: TypeGenerator[T, n.N]{ type Result = TResult }, fl: FromTraversable[TResult]): Option[TResult] = l.toHList[tg.Result]
- // Exiting paste mode, now interpreting.
- import shapeless.ops.traversable.FromTraversable
- import shapeless.syntax.std.traversable._
- import shapeless._
- defined class TypeGenerator
- defined trait LowPriorityTypeGenerator
- defined object TypeGenerator
- toHList: [T, TResult <: shapeless.HList](l: List[T], n: shapeless.Nat)(implicit tg: TypeGenerator[T,n.N]{type Result = TResult}, implicit fl: shapeless.ops.traversable.FromTraversable[TResult])Option[TResult]
- scala> val list = "a" :: "b" :: "c" :: Nil
- list: List[String] = List(a, b, c)
- scala> toHList(list, Nat(3))
- res0: Option[this.Result] = Some(a :: b :: c :: HNil)
- scala> toHList(list, 3)
- res1: Option[this.Result] = Some(a :: b :: c :: HNil)
- scala> val hList = 1 :: "abc" :: 'd :: HNil
- hList: shapeless.::[Int,shapeless.::[String,shapeless.::[Symbol,shapeless.HNil]]] = 1 :: abc :: 'd :: HNil
- scala> toHList("x" :: "y" :: "z" :: Nil, 3).map{ _ zip hList }
- res2: Option[shapeless.::[(String, Int),shapeless.::[(String, String),shapeless.::[(String, Symbol),shapeless.HNil]]]] = Some((x,1) :: (y,abc) :: (z,'d) :: HNil)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement