Skip to content

Instantly share code, notes, and snippets.

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 carlosypunto/4ddc0187fdc9a3e8e5e7 to your computer and use it in GitHub Desktop.
Save carlosypunto/4ddc0187fdc9a3e8e5e7 to your computer and use it in GitHub Desktop.
//: Sample based on Function Composition snippet from objc.io: http://www.objc.io/snippets/2.html
import Foundation
func getContents(url: String) -> String {
return NSString(contentsOfURL: NSURL(string: url)!, encoding: NSUTF8StringEncoding, error: nil)! as String
}
func lines(input: String) -> [String] {
return input.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
}
// WITHOUT COMPOSITION ---------------------------------------------------------------------------------------
let linesInURL = { url in count(lines(getContents(url))) }("http://www.objc.io/books")
// CASE A (process from right to left) -----------------------------------------------------------------------
infix operator <<< { associativity left }
func <<< <A, B> (f: A -> B, x: A) -> B {
return f(x)
}
func <<< <A, B, C> (f: B -> C, g: A -> B) -> (A -> C) {
return { x in f(g(x)) }
}
let linesInURL2 = (count <<< lines <<< getContents)("http://www.objc.io/books")
let linesInURL3 = count <<< lines <<< getContents <<< "http://www.objc.io/books"
// CASE B (process from left to right) -----------------------------------------------------------------------
infix operator >>> { associativity left }
func >>> <A, B> (s: A, f: A -> B) -> B {
return f(s)
}
func >>> <A, B, C> (f: A -> B, g: B -> C) -> (A -> C) {
return { x in g(f(x)) }
}
let linesInURL4 = "http://www.objc.io/books" >>> getContents >>> lines >>> count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment