Forked from ColinEberhardt/gist:b4bf4e4566ffa88afcda
Created
November 10, 2015 02:55
-
-
Save LawrenceHan/9857594f6826c9f96084 to your computer and use it in GitHub Desktop.
Pipe forward operator and curried free functions = fluent interface
This file contains hidden or 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
// meet Stringy - a simple string type with a fluent interface | |
struct Stringy { | |
let content: String | |
init(_ content: String) { | |
self.content = content | |
} | |
func append(appendage: Stringy) -> Stringy { | |
return Stringy(self.content + " " + appendage.content) | |
} | |
func printMe() { | |
println(content) | |
} | |
} | |
////////////////////////////////////////////////////////////////////// | |
// Stringy in action ... | |
var greeting = Stringy("Hi") | |
greeting.append(Stringy("how")) | |
.append(Stringy("are")) | |
.append(Stringy("you?")) | |
.printMe() // => "Hi how are you?" | |
// A lovely fluent interface! | |
////////////////////////////////////////////////////////////////////// | |
// Now what append and printMe were 'free functions'? | |
func appendFreeFunction(a: Stringy, b: Stringy) -> Stringy { | |
return Stringy(a.content + " " + b.content) | |
} | |
func printMe(a: Stringy) { | |
a.printMe() | |
} | |
// Stringy with free functions in action ... | |
printMe( | |
appendFreeFunction( | |
appendFreeFunction( | |
appendFreeFunction(greeting, Stringy("how")), Stringy("are")), Stringy("you?"))) | |
// => "Hi how are you?" | |
// Yuck - we no longer have the fluent interface, with a real mess of brackets | |
////////////////////////////////////////////////////////////////////// | |
// Pipe forward | |
// modify the free functions, turnign them into curried functions | |
func appendCurriedFreeFunction(a: Stringy)(b: Stringy) -> Stringy { | |
return Stringy(b.content + " " + a.content) | |
} | |
// and define a pipe forward operator | |
infix operator |> { associativity left } | |
func |><X> (stringy: Stringy, transform: Stringy -> X) -> X { | |
return transform(stringy) | |
} | |
// we now have free functions AND a fluent interface | |
greeting | |
|> appendCurriedFreeFunction(Stringy("how")) | |
|> appendCurriedFreeFunction(Stringy("are")) | |
|> appendCurriedFreeFunction(Stringy("you?")) | |
|> printMe // => "Hi how are you?" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment