Monday, January 16, 2012

Basic Scala HList

I've been trying to follow this excellent article:
http://apocalisp.wordpress.com/2010/07/08/type-level-programming-in-scala-part-6b-hlist%C2%A0folds/

But I couldn't quite make the jump from the part (a) to part (b).

To try to get to an intermediate mental step, I decided to try to implement an HList with just an append method. Here it is:

sealed trait HList {
  type Appended[L] <: HList
  def append[L](l: L) :Appended[L]
}

final case class HCons [H, T<:HList] (head: H, tail: T) extends HList {
  type Appended[L] = HCons[H, tail.Appended[L]]
  
  def ::[C](c: C): HCons[C, HCons[H, T]] = HCons(c, this)
  def append[L](l: L) = HCons(head, tail.append(l))
}

sealed class HNil extends HList {
  type Appended[L] = HCons[L, HNil]
  
  def ::[C](c: C): HCons[C, HNil] = HCons(c, this)
  def append[L](l: L): Appended[L] = l :: HNil
  
  override def toString = "HNil"
}
object HNil extends HNil

object test {
  def main (args:Array[String]) {
    val a = "Test" :: 24 :: HNil
    val b: HCons[String, HCons[Int, HCons[String, HNil]]] = a append "January"
  }
}

Now that I got that working (some good practice, I suppose), I might be able to make sense of the original article.

No comments:

Post a Comment