Functional Snippet #6: Currying
Turning a function that takes multiple arguments into a series of functions that each take one argument is called currying. For example, take this function with three arguments:
func login(email: String, pw: String, success: (Bool )-> ())
We can turn it into a series of functions where the arguments can be applied one after another using Swift's special syntax for curried functions:
func curriedLogin1(email: String);(pw: String)(success: Bool -> ())
More interestingly, we can also write a generic function that does the currying for us. The following one works on functions with three arguments, but we could write variants for any number of arguments:
func curry<A, B, C, R>(f: (A, B, C) -> R) -> (A )-> (B )-> (C )-> R {
return { a in { b in { c in f(a, b, c) } } }
}
let curriedLogin2 = curry(login)
Now we can apply the arguments one by one:
let f = curriedLogin2("foo")("bar")
f { println("success: \($0)") }
You're actually using this pattern all the time without even noticing: instance methods in Swift are curried functions that take the instance as first argument.
Stay tuned for next week's snippet for a cool application of this.