Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save carlosypunto/4ddc0187fdc9a3e8e5e7 to your computer and use it in GitHub Desktop.

Select an option

Save carlosypunto/4ddc0187fdc9a3e8e5e7 to your computer and use it in GitHub Desktop.

Revisions

  1. carlosypunto created this gist Mar 31, 2015.
    40 changes: 40 additions & 0 deletions Swift Function composition operator direction
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    //: 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