Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. /// Playground - noun: a place where people can play
  2. /// An un-parser for things is a continuation on strings...
  3.  
  4. precedencegroup CompositionPrecedence {
  5. associativity: right
  6. higherThan: BitwiseShiftPrecedence
  7. }
  8.  
  9. prefix operator <<
  10. postfix operator >>
  11. infix operator • : CompositionPrecedence
  12.  
  13. prefix func << <A>(_ x : A) -> A { return x }
  14. postfix func >> <A>(_ x : A) -> A { return x }
  15.  
  16. func • <A, B, C>(_ f : @escaping (B) -> C, _ g : @escaping (A) -> B) -> (A) -> C {
  17. return { x in f(g(x)) }
  18. }
  19.  
  20. //: Olivier Danvy proposes a neat solution to a problem that would seem, at first blush,
  21. //: to require dependent types to solve. Namely, a typesafe printf function, which is
  22. //: usually implemented by parsing the format string into a functional that constructs an
  23. //: arrow with a hole for each argument. Danvy instead uses continuation-passing to
  24. //: construct a small automata capable of running format string "programs". The result is
  25. //: the same, albeit with some minor amounts of syntactic sugar to make the whole thing
  26. //: look nice (<< >>).
  27.  
  28. //: Inline string literals
  29. func lit<A>(_ x : String) -> (@escaping (String) -> A) -> (String) -> A {
  30. return { k in
  31. return { s in k(s + x) }
  32. }
  33. }
  34.  
  35. //: \n | Appends a newline character.
  36. //:
  37. //: Takes a continuation passing the current string and returns a
  38. //: continuation that appends a newline character to the string.
  39. func eol<A>(_ k : @escaping (String) -> A) -> (String) -> A {
  40. return { x in k(x + "\n") }
  41. }
  42.  
  43. //: %d | Appends an integer to the format string.
  44. func int<A>(_ k : @escaping (String) -> A) -> (String) -> (Int) -> A {
  45. return { s in { x in k(s + x.description) } }
  46. }
  47.  
  48. //: %s | Appends a string to the format string.
  49. func str<A>(_ k : @escaping (String) -> A) -> (String) -> (String) -> A {
  50. return { s in { x in k(s + x) } }
  51. }
  52.  
  53. //: Execute the continuation stack and return the final format string.
  54. func format<A>(_ f : (@escaping (String) -> String) -> (String) -> A) -> A {
  55. return f({ $0 })("")
  56. }
  57.  
  58. let x : Int = 2
  59. let y : Int = 21
  60. let z : Int = 42
  61. let s : String = ", right?"
  62. let f = format(<<(int • lit(" * ") • int • lit(" = ") • int • str • eol)>>)(x)(y)(z)(s)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement