Skip to content

Instantly share code, notes, and snippets.

@biboudis
Last active January 30, 2018 14:54
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 biboudis/344949a9d9f022191b9fd29c336fd13d to your computer and use it in GitHub Desktop.
Save biboudis/344949a9d9f022191b9fd29c336fd13d to your computer and use it in GitHub Desktop.
A simple type-safe formatter in Scala based on the "Functional Unparsing" paper by Olivier Danvy
// A simple type-safe formatter in Scala based on the "Functional Unparsing" paper by Olivier Danvy
// http://cs.au.dk/~danvy/DSc/16_danvy_jfp-1998.pdf
object Test {
def eol[A](k: String => A)(s: String): A = {
k(s + "\n")
}
def lit[A](x: String)(k: String => A)(s: String): A = {
k(s + x)
}
def int[A](k: String => A)(s: String)(x: Int): A = {
k(s + x.toString)
}
def str[A](k: String => A)(s: String)(x: String): A = {
k(s + x)
}
def format[A](p: (String => String) => (String) => A): A = {
p(identity[String])("")
}
def main(args: Array[String]): Unit = {
val p1: (String => String) => (String) => (Int) => String = int _
val p2: (String => String) => (String) => (Int) => Int => String = int[Int => String] _ compose int[String] _
val p3: (String => String) => (String) => (Int) => String = int[String] _ compose eol[String] _
val p4: (String => String) => (String) => (Int) => String = int[String] _ compose lit[String](" is the answer.") _ compose eol[String] _
val p5: (String => String) => (String) => (Int) => String => String = int[String => String] _ compose str[String] _ compose eol[String] _
print(format(p1)(1))
print(format(p2)(2)(99))
print(format(p3)(3))
print(format(p4)(4))
print(format(p5)(42)(" is the answer again."))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment