Skip to content

Instantly share code, notes, and snippets.

@dragisak
Created March 29, 2015 06:01
Show Gist options
  • Save dragisak/10a3a5837662cdaa29db to your computer and use it in GitHub Desktop.
Save dragisak/10a3a5837662cdaa29db to your computer and use it in GitHub Desktop.
Type level programming in Scala: Heterogeneous list
package com.dragisak.hlist
object HList {
sealed trait HList {
type prepend[A] <: HList
def ::[A](a: A) :prepend[A]
}
case class HCons[H, Tail <: HList](head: H, tail: Tail) extends HList {
override type prepend[A] = HCons[A, HCons[H, Tail]]
override def ::[A](a: A): prepend[A] = HCons(a, this)
}
case object HNil extends HList {
override type prepend[A] = HCons[A, HNil.type ]
override def ::[A](a: A): prepend[A] = HCons(a, this)
}
}
@dragisak
Copy link
Author

Example:

import com.dragisak.hlist.HList._

val x = 2 :: false :: 2 :: Some(4) :: "foo" :: HNil


val a = x.head // Int
val b = x.tail.head // Boolean

@jiamingd
Copy link

jiamingd commented Jun 9, 2017

Clear and neat!

@codedoneteam
Copy link

Nice! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment