Alejandro Martinez

21 December, 2015SwiftFunctional Programming🕐 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> {
    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")

👉🏻 If you have any feedback you can reach me at alexito4


Alejandro Martinez

Buka pintu