21 December 2015 1min read

Functions are Functors

We are used to treat closures as first class citizens in our code. Same goes to functions as they are interchangeable. But we often don’t think of them as actual types. So they also can play with the rules and abstractions that we usually attach to classes or structs.

So yes, a function of type (I -> O) is a Functor

struct Function<I, O> {
    let closure: I -> O
    
    func map<U>(f: Function<O, U>) -> Function<I, U> {
        return Function<I, U> {
            f.closure(self.closure($0))
        }
    }
    
    func call(i: I) -> O {
        return closure(i)
    }
}

func length(i: String) -> Int {
    return i.characters.count
}

func isPositive(i: Int) -> Bool {
    return i > 0
}

let f1 = Function(closure: length)
let f2 = Function(closure: isPositive)
let isEmpty = f1.map(f2)
isEmpty.call("hola")

If you enjoyed this post

Continue reading