Otávio C.

Function Currying in Objective-C

Function Currying and uncurrying have been extensively discussed since Apple introduced Swift last year. I won’t delve into this topic deeply because there are some great resources about it on the Internet.

But, briefly, what is currying? It’s a technique that transforms a function that takes several arguments into a sequence of functions, each with a single argument. The result is a chain of functions returning functions. It’s beautiful, it’s mathematics!

Below is a simple example in Swift:

func add(_ a: Int) -> (Int) -> (Int) -> Int {
    { b in { c in a + b + c } }
}

let addTwo = add(2) // Int -> Int -> Int
let addFive = addTwo(3) // Int -> Int
let result = addFive(4) // 9

print("result = \(result)") // result = 9

And the same example in Objective-C:

typedef NSInteger(^FuncInt2Int)(NSInteger);
typedef FuncInt2Int(^FuncInt2Int2Int)(NSInteger);

FuncInt2Int2Int(^add)(NSInteger) = ^FuncInt2Int2Int(NSInteger a) {
    return ^FuncInt2Int(NSInteger b) {
        return ^NSInteger(NSInteger c) {
            return a + b + c;
        };
    };
};

FuncInt2Int2Int addTwo = add(2); // Int -> Int -> Int
FuncInt2Int addFive = addTwo(3); // Int -> Int
NSInteger result = addFive(4); // 9

NSLog(@"result = %ld", result); // result = 9

The Swift version is minimal and elegant. But the Objective-C one has its charm, doesn’t it?

#Swift