Alexito's World

A world of coding 💻, by Alejandro Martinez

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 { let closure: I -> O func map(f: Function) -> Function { return Function { 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 ="hola")