Advertisement
Guest User

Untitled

a guest
May 4th, 2015
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1.  
  2. // meet Stringy - a simple string type with a fluent interface
  3. struct Stringy {
  4. let content: String
  5.  
  6. init(_ content: String) {
  7. self.content = content
  8. }
  9.  
  10. func append(appendage: Stringy) -> Stringy {
  11. return Stringy(self.content + " " + appendage.content)
  12. }
  13.  
  14. func printMe() {
  15. println(content)
  16. }
  17. }
  18.  
  19. //////////////////////////////////////////////////////////////////////
  20. // Stringy in action ...
  21.  
  22. var greeting = Stringy("Hi")
  23.  
  24. greeting.append(Stringy("how"))
  25. .append(Stringy("are"))
  26. .append(Stringy("you?"))
  27. .printMe() // => "Hi how are you?"
  28.  
  29. // A lovely fluent interface!
  30.  
  31. //////////////////////////////////////////////////////////////////////
  32. // Now what append and printMe were 'free functions'?
  33.  
  34. func appendFreeFunction(a: Stringy, b: Stringy) -> Stringy {
  35. return Stringy(a.content + " " + b.content)
  36. }
  37.  
  38. func printMe(a: Stringy) {
  39. a.printMe()
  40. }
  41.  
  42. // Stringy with free functions in action ...
  43. printMe(
  44. appendFreeFunction(
  45. appendFreeFunction(
  46. appendFreeFunction(greeting, Stringy("how")), Stringy("are")), Stringy("you?")))
  47. // => "Hi how are you?"
  48.  
  49. // Yuck - we no longer have the fluent interface, with a real mess of brackets
  50.  
  51. //////////////////////////////////////////////////////////////////////
  52. // Pipe forward
  53.  
  54. // modify the free functions, turnign them into curried functions
  55. func appendCurriedFreeFunction(a: Stringy)(b: Stringy) -> Stringy {
  56. return Stringy(b.content + " " + a.content)
  57. }
  58.  
  59. // and define a pipe forward operator
  60. infix operator |> { associativity left }
  61.  
  62. func |><X> (stringy: Stringy, transform: Stringy -> X) -> X {
  63. return transform(stringy)
  64. }
  65.  
  66. // we now have free functions AND a fluent interface
  67. greeting
  68. |> appendCurriedFreeFunction(Stringy("how"))
  69. |> appendCurriedFreeFunction(Stringy("are"))
  70. |> appendCurriedFreeFunction(Stringy("you?"))
  71. |> printMe // => "Hi how are you?"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement