Skip to content

Instantly share code, notes, and snippets.

@logicalguess
Created September 23, 2017 05:00
Show Gist options
  • Save logicalguess/96773389fb888346b3be19c240d629f5 to your computer and use it in GitHub Desktop.
Save logicalguess/96773389fb888346b3be19c240d629f5 to your computer and use it in GitHub Desktop.
Shapeless HList containers
package logicalguess.union
import shapeless.ops.hlist.Selector
import shapeless.{::, HList, HNil, Typeable}
import scala.reflect.runtime.universe._
trait HListMContainer {
type L <: HList
val hv: L
val t: Typeable[L]
def getType = t.describe
def add[In : TypeTag](in: In)(implicit t1: Typeable[In :: L]) = new HListMContainer {
override type L = In :: HListMContainer.this.L
override val hv: L = in :: HListMContainer.this.hv
override val t = Typeable[L]
//println(t.describe)
}
def lastAddedOfType[In](in: In)(implicit ev: Selector[L, In]) = {
hv.select(ev).equals(in)
}
}
object HListMContainer {
def empty = new HListMContainer {
override type L = HNil
override val hv = HNil
override val t = Typeable[HNil]
}
}
object HListMContainerTest {
def main(args: Array[String]): Unit = {
val c = HListMContainer.empty.add(1).add("a").add("b").add(2)
println(c.getType)
//Int :: String :: String :: Int :: HNil
println(c.hv)
//2 :: b :: a :: 1 :: HNil
println(c.lastAddedOfType(1)) //false
println(c.lastAddedOfType("a")) //false
println(c.lastAddedOfType("b")) //true
println(c.lastAddedOfType(2)) //true
}
}
package logicalguess.union
import shapeless.ops.hlist.Selector
import shapeless.{::, HList, HNil, Typeable}
import scala.reflect.runtime.universe._
trait HListPContainer[L <: HList] {
val hv: L
def getType(implicit t: Typeable[L]) = t.describe
def add[In : TypeTag](in: In)= new HListPContainer[In :: L] {
override val hv: In :: L = in :: HListPContainer.this.hv
}
def lastAddedOfType[In](in: In)(implicit ev: Selector[L, In]) = hv.select(ev).equals(in)
}
object HListPContainer {
def empty = new HListPContainer[HNil] {
override val hv = HNil
}
}
object HListPContainerTest {
def main(args: Array[String]): Unit = {
val c = HListPContainer.empty.add(1).add("a").add("b").add(2)
println(c.getType)
//Int :: String :: String :: Int :: HNil
println(c.hv)
//2 :: b :: a :: 1 :: HNil
println(c.lastAddedOfType(1)) //false
println(c.lastAddedOfType("a")) //false
println(c.lastAddedOfType("b")) //true
println(c.lastAddedOfType(2)) //true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment