Functional Snippet #2: Function Composition

In functional programming, we often want to combine multiple small, independent functions into a new function. For example, let’s say we have a function for getting the contents of a URL, a function for turning a string into an array of lines, and a function for counting elements. We can compose those functions into a new function that counts the number of lines in a URL:

func getContents(url: String) -> String {
    return NSString(contentsOfURL: NSURL(string: url), 
                    encoding: NSUTF8StringEncoding, error: nil)

func lines(input: String) -> [String] {
    return input.componentsSeparatedByCharactersInSet(

let linesInURL = { url in countElements(lines(getContents(url))) }
linesInURL("") // Returns 731

Because function composition is such a common thing, functional programmers defined a custom operator for it.

infix operator >>> { associativity left }
func >>> <A, B, C>(f: B -> C, g: A -> B) -> A -> C {
    return { x in f(g(x)) }

Now, we can get rid of all the nested parentheses, and write our example like this:

let linesInURL2 = countElements >>> lines >>> getContents
linesInURL2("") // Returns 470

Most recent posts