Created
August 26, 2016 10:51
-
-
Save rexim/abafc00d2861ee337b750d403ea5ec61 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object TermOutputHelper { | |
def smartShowTerm(term: LambdaTerm): String = { | |
val (prefix, value) = decode(term) | |
s"$prefix: $value" | |
} | |
private def decode(term: LambdaTerm): (String, String) = { | |
decoders | |
.map(_(term)) // apply each encoder to the term | |
.dropWhile(_.isEmpty) // get rid of false results | |
.headOption // try to get the head | |
.flatMap(identity) // flatten Option | |
.getOrElse(("term", term.toString)) // get result or return default | |
} | |
private val decoders: Stream[Decoder[_]] = | |
Stream( | |
Decoder[Char] ("char", c => s"'$c'"), | |
Decoder[Int] ("number", _.toString), | |
Decoder[String] ("string", s => s"""\"$s\""""), | |
Decoder[Seq[Int]] ("numbers", _.mkString("[", ",", "]")), | |
Decoder[Seq[LambdaTerm]] ("elements", _.map(decode(_)._2).mkString("[", ",", "]")), | |
Decoder[(LambdaTerm, LambdaTerm)] ("pair", { case (a, b) => s"(${decode(a)._2}, ${decode(b)._2})" }) | |
) | |
private case class Decoder[T](prefix: String, transform: T => String)(implicit unT: Unliftable[T]) { | |
def apply(term: LambdaTerm): Option[(String, String)] = unT.unapply(term).map(transform).map((prefix, _)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment