Skip to content

Instantly share code, notes, and snippets.

@filippovitale
Created January 15, 2015 10:08
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 filippovitale/4dd8a095bf66b3153101 to your computer and use it in GitHub Desktop.
Save filippovitale/4dd8a095bf66b3153101 to your computer and use it in GitHub Desktop.
/**
* reference: http://www.cs.ox.ac.uk/ralf.hinze/publications/GGTries/Encode.lhs
*/
object GenTrie {
sealed trait Bit
case object △ extends Bit
case object ▲ extends Bit
type Bits = List[Bit]
trait Encodable[A] {
def encode(a: A): List[Bit]
}
implicit val encodableUnit = new Encodable[Unit] {
override def encode(x: Unit): List[Bit] = List()
}
implicit val encodableBit = new Encodable[Bit] {
override def encode(x: Bit): List[Bit] = List(x)
}
implicit def encodableList[V](implicit v0: Encodable[V]) = new Encodable[List[V]] {
override def encode(x: List[V]): List[Bit] = x match {
case Nil => List(△)
case x :: xs => List(▲) ++ v0.encode(x) ++ encode(xs)
}
}
implicit val encodablePosInt = new Encodable[Int] {
override def encode(x: Int): List[Bit] = x.toBinaryString.toList.map {
case '0' => △
case '1' => ▲
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment