Last active
January 30, 2018 14:54
-
-
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
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
// 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