Skip to content

Instantly share code, notes, and snippets.

@aloiscochard
Created January 3, 2012 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aloiscochard/1554658 to your computer and use it in GitHub Desktop.
Save aloiscochard/1554658 to your computer and use it in GitHub Desktop.
Scala Association Heterogeneous List (map with heterogeneous values)
// Association Heterogeneous List
object AHListTest {
object AHList {
def apply[K]() = new AHNil[K]()
}
sealed trait AHList[K] {
def get[V : Manifest](k: K): Option[V] = None
def get[V : Manifest](k: K, default: V): V = get[V](k).getOrElse(default)
def put[V : Manifest](k: K, v: V) = AHCons(k -> v, this)
}
final class AHNil[K] extends AHList[K] {
def ::[V : Manifest](v : Tuple2[K, V]) = AHCons(v, this)
}
def AHNil[K] = new AHNil[K]()
final case class AHCons[K, V : Manifest, T <: AHList[K]](head : Tuple2[K, V], tail : T) extends AHList[K] {
def ::[V : Manifest](v : Tuple2[K, V]) = AHCons(v, this)
override def get[L : Manifest](key: K): Option[L] = {
if (head._1 == key && manifest[V] <:< manifest[L]) Some(head._2.asInstanceOf[L])
else tail.get[L](key)
}
}
type ::[K, V, T <: AHList[K]] = AHCons[K, V, T]
}
/*
scala> val list = ("age" -> 26) :: ("name" -> "Alois") :: AHNil[String]
list: AHListTest.AHCons[String,Int,AHListTest.AHCons[String,java.lang.String,AHListTest.AHNil[String]]] = AHCons((age,26),AHCons((name,Alois),AHListTest$AHNil@2f0f94a0))
scala> list.head._2
res0: Int = 26
scala> list.tail.head._2
res1: java.lang.String = Alois
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment