Advertisement
NLinker

HList in scala

Dec 4th, 2017
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.05 KB | None | 0 0
  1. Concat_via_type_classes
  2.   trait HList
  3.   case class HCons[H, T <: HList](head: H, tail: T) extends HList
  4.   case object HNil extends HList
  5.   type HNil = HNil.type
  6.  
  7.   // type class
  8.   trait Concat[L1 <: HList, L2 <: HList] {
  9.     type Out <: HList
  10.     def apply(l1: L1, l2: L2): Out
  11.   }
  12.  
  13.   object Concat {
  14.     type Aux[L1 <: HList, L2 <: HList, Out0 <: HList] = Concat[L1, L2] { type Out = Out0 }
  15.  
  16.     def apply[L1 <: HList, L2 <: HList, Out0 <: HList](f: (L1, L2) => Out0): Aux[L1, L2, Out0] = new Concat[L1, L2] {
  17.       override type Out = Out0
  18.       override def apply(l1: L1, l2: L2): Out = f(l1, l2)
  19.     }
  20.  
  21.     implicit def hNilConcat[L <: HList]: Aux[HNil, L, L] = Concat((_, l) => l)
  22.  
  23.     implicit def hConsConcat[H, T <: HList, L <: HList, T_concatL <: HList](implicit
  24.       concat: Aux[T, L, T_concatL]): Aux[HCons[H, T], L, HCons[H, T_concatL]] =
  25.       Concat { case (HCons(h, t), l) => HCons(h, concat(t, l)) }
  26.  
  27.     object op {
  28.       implicit class ConcatOp[L1 <: HList](l1: L1) {
  29.         def concat[L2 <: HList](l2: L2)(implicit concat: Concat[L1, L2]): concat.Out = concat(l1, l2)
  30.       }
  31.     }
  32.   }
  33.  
  34.   import Concat.op._
  35.   HCons(1, HCons("a", HCons(true, HNil))).concat(HCons(1L, HCons(1.0, HNil)))
  36. Concat_via_type_projections
  37.   trait HList {
  38.     type Concat[L <: HList] <: HList
  39.     def concat[L <: HList](l: L): Concat[L]
  40.   }
  41.  
  42.   case class HCons[H, T <: HList](head: H, tail: T) extends HList {
  43.     override type Concat[L <: HList] = HCons[H, T#Concat[L]]
  44.     override def concat[L <: HList](l: L): Concat[L] = HCons(head, tail.concat(l))
  45.   }
  46.  
  47.   case object HNil extends HList {
  48.     override type Concat[L <: HList] = L
  49.     override def concat[L <: HList](l: L): Concat[L] = l
  50.   }
  51.   type HNil = HNil.type
  52.  
  53.   HCons(1, HCons("a", HCons(true, HNil))).concat(HCons(1L, HCons(1.0, HNil)))
  54. HList
  55.   trait HList
  56.   case class HCons[H, T <: HList](head: H, tail: T) extends HList
  57.   case object HNil extends HList
  58.   type HNil = HNil.type
  59.  
  60.   HCons(1, HCons("a", HCons(true, HNil))) : HCons[Int, HCons[String, HCons[Boolean, HNil]]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement